链接
传送门
题意
有\(n\)个城市,要从第1个出发,经过\(k\)天到第\(n\)个。给出每天城市间旅行的花费,输出最小的话费值。
思路
定义\(dp[d][i]\)为第\(d\)天到城市\(i\)的最小花费。如果第\(d + 1\)天在城市\(i\)与城市\(j\)之间有航线,则可以转移至\(dp[d + 1][j]\)。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #include <cstdio> #include <cstring> #include <algorithm> using namespace std;
typedef long long LL; const int inf = 0x3f3f3f3f; const int maxn = 12; const int maxd = 35; const int maxk = 1010; int c[maxn][maxn][maxd], num[maxn][maxn]; int dp[maxk][maxn];
int main() { freopen("/Users/wangchengrui/Desktop/in.txt", "r", stdin); int n, k, t = 0; while (~scanf("%d%d", &n, &k) && (n || k)) { for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { if (i != j) { scanf("%d", &num[i][j]); for (int d = 0; d < num[i][j]; ++d) { scanf("%d", &c[i][j][d]); } } } } memset(dp, 0x3f, sizeof dp); dp[0][1] = 0; for (int d = 1; d <= k; ++d) { for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { if (i != j) { int x = (d - 1) % num[i][j]; if (c[i][j][x] != 0) { dp[d][j] = min(dp[d][j], dp[d - 1][i] + c[i][j][x]); } } } } } printf("Scenario #%d\n", ++t); if (dp[k][n] != inf) { printf("The best flight costs %d.\n\n", dp[k][n]); } else { puts("No flight possible.\n"); } } return 0; }
|