Codeforces Round #374 (Div. 2) C. Journey DP

C. Journey

链接:

http://codeforces.com/contest/721/problem/C

题意:

给你一个n点m边的图,让你从1走到n,找到一条经过尽量多点的路径,且路径边权和小于等于T

然后输出路径。

题解:

直接DP,DP[i][j]表示在i点,当前经过了j个点的最小代价是多少

代码:

 1 #include <iostream>  
 2 #include <stack>   
 3 #include <cstring>  
 4 using namespace std;
 5 
 6 const int maxn = 5e3 + 7;
 7 struct Edge { int u, v, t; }E[maxn];
 8 int dp[maxn][maxn];
 9 int pre[maxn][maxn];
10 stack<int> ans;
11 
12 int main()
13 {
14     int n, m, T;
15     cin >> n >> m >> T;
16     for (int i = 0; i < m; i++)
17         cin >> E[i].u >> E[i].v >> E[i].t;
18     memset(dp, 0x3f, sizeof(dp));
19     memset(pre, -1, sizeof(pre));
20     dp[1][1] = 0;
21     int pos;
22     for (int i = 2; i <= n; i++) {
23         for (int j = 0; j < m; j++) {
24             int u = E[j].u;
25             int v = E[j].v;
26             int t = E[j].t;
27             if (dp[i - 1][u] + t < dp[i][v]) {
28                 dp[i][v] = dp[i - 1][u] + t;
29                 pre[i][v] = u;
30             }
31         }
32         if (dp[i][n] <= T)  pos = i;
33     }
34     cout << pos << endl;
35     int u = n;
36     while (u != -1) {
37         ans.push(u);
38         u = pre[pos--][u];
39     }
40     while (!ans.empty()){
41         cout << ans.top() << " ";
42         ans.pop();
43     }
44     return 0;
45 }

 

posted @ 2016-10-07 16:31  Flowersea  阅读(227)  评论(0编辑  收藏  举报