这个题目阶段性很明显,就是一个图的遍历
状态:dp[i][j] 表示第i天到达城市j的最小花费
状态转移:dp[i][j] = dp[i-1][z]+cost[z][j]
ans = dp[n][k]
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 11
#define MAXK 1001
#define INF 549755813888
typedef struct DAYTYPE_ {
long long cnt, arr[MAXK];
}DAYTYPE;
long long dp[MAXK][MAXN];
DAYTYPE price[MAXN][MAXN];
long long get_price(const int &u, const int &v, const int &day)
{
if( u == v ) {
return INF;
}
int val = (day%price[u][v].cnt)? price[u][v].arr[ day%price[u][v].cnt ] : price[u][v].arr[ price[u][v].cnt ];
return (val)? val : INF;
}
long long dynamic_programming(const int &n, const int &k)
{
for(int i = 2; i <= n; i ++) {
dp[1][i] = (price[1][i].arr[1])? price[1][i].arr[1] : INF;
}
for(int i = 2; i <= k; i ++) {
for(int j = 1; j <= n; j ++) { dp[i][j] = INF;
for(int z = 1; z <= n; z ++) {
dp[i][j] = min(dp[i][j], (-1 == dp[i-1][z])? INF : dp[i-1][z] + get_price(z, j, i));
}
}
}
return dp[k][n];
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
long long rst;
int n, k, cnt, cas(1);
while( scanf("%d %d", &n, &k) && n && k ) {
memset(price, -1, sizeof(price)); memset(dp, -1, sizeof(dp));
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) {
if( i == j ) {
continue;
}
scanf("%lld", &price[i][j].cnt);
for(int k = 1; k <= price[i][j].cnt; k ++) {
scanf("%lld", &price[i][j].arr[k]);
}
}
}
printf("Scenario #%d\n", cas ++);
if( (rst = dynamic_programming(n, k)) >= INF ) {
printf("No flight possible.\n\n"); continue;
}
printf("The best flight costs %lld.\n\n", rst);
}
return 0;
}