uva590

来源:互联网 发布:左飞 算法之美pdf 编辑:程序博客网 时间:2024/06/08 13:56

题目大意:
给定两个数n,k,n个城市,k次航班,然后给出n*(n-1)条航班记录,前(n-1)行代表第一个城市分别到其他城市的航班,如果消费为0,则代表没有航班,例如第一个样例,前两行表第一个城市到第二个城市和打三个城市的所有航班,接下来的(n-1)行,代表第二个城市到第一个城市和第三个城市的,现在要求出从第一个城市出发,经过k次航班,到达第n个城市所需要的最小花费是多少?

思路:
状态转移方程:dp[i][j]表示经过j次航班,到达城市i的最小花费
dp[i][j]初始为无穷大,dp[1][0]=0;
dp[i][j]=min(dp[i-1][j]+cost[i][j][c],dp[i][j]);
cost[i][j][c]表示从城市i到城市j第c天所需要花费的钱。

代码:

#include <iostream>using namespace std;#include <cstring>#include <stdio.h>const int MAXN = 1005;const int INF = 0x3f3f3f3f;const int N = 15;int d[N][MAXN],day[N][N],cost[N][N][MAXN];int n,k;int dp() {    for(int q = 1; q <= k; q++ ) {        for(int i = 1; i <= n; i++) {            for(int j = 1; j <= n; j++) {                if(i == j)                    continue;                int temp = (q - 1) % day[j][i];                if(cost[j][i][temp] && d[j][q - 1] != INF)                    d[i][q] = min(d[i][q],d[j][q - 1] + cost[j][i][temp]);            }        }    }    return d[n][k];}int main() {    int T = 1;    bool first = true;    while(scanf("%d %d",&n,&k) && n + k) {        /*if(first)            first = false;        else            printf("\n");*/        memset(cost,0,sizeof(cost));        for(int i = 0; i <= n; i++)            for(int j = 0; j <= k; j++)                d[i][j] = INF;        d[1][0] = 0;        for(int i = 1; i <= n; i++) {            for(int j = 1; j <= n; j++) {                if(i != j) {                    scanf("%d",&day[i][j]);                    for(int q = 0; q < day[i][j]; q++) {                        scanf("%d",&cost[i][j][q]);                    }                }            }        }        int ans = dp();        printf("Scenario #%d\n",T++);        if(ans != INF)            printf("The best flight costs %d.\n\n",ans);        else            printf("No flight possible.\n\n");    }    return 0;}
0 0
原创粉丝点击