DAG图拓扑 + dp
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<vector> #include<queue> #include<stack> using namespace std; int n, m, T; struct Node { int to; int dis; Node(){} Node(int x, int y) { to = x; dis = y; } }; const int maxn = 5050; const int INF = 0x3f3f3f3f; int indeg[maxn]; queue<int> q; vector<Node> g[maxn]; int dp[maxn][maxn]; int pre[maxn][maxn]; void topsort() { /* for(int i = 1; i <= n; i++) if(!indeg[i]) cout << i << " "; cout << endl; */ queue<int> tmp; for(int i = 1; i <= n; i++) { if(indeg[i] == 0) { cout << "insert into tmp: " << i << endl; tmp.push(i); } } cout << "tmp seq is: " << endl; while(!tmp.empty()) { int u = tmp.front(); q.push(u); tmp.pop(); cout << u << " " ; cout << g[u].size() << " "; for(int i = 0; i < (int)g[u].size(); i++) { int t = g[u][i].to; indeg[t]--; if(!indeg[t]) tmp.push(t); } } cout << endl; } int main() { int n; cin >> n >> m >> T; int a, b, c; for(int i = 0; i < m; i++) { cin >> a >> b >> c; g[a].push_back(Node(b, c)); //correct indeg[b]++; } //topsort(); //wrong queue<int> tmp; for(int i = 1; i <= n; i++) { if(indeg[i] == 0) { tmp.push(i); } } //cout << "tmp seq is: " << endl; while(!tmp.empty()) { int u = tmp.front(); q.push(u); tmp.pop(); //cout << u << " " ; for(int i = 0; i < (int)g[u].size(); i++) { int t = g[u][i].to; indeg[t]--; if(!indeg[t]) tmp.push(t); } } for(int i = 1; i <= n; i++) for(int j = 0; j < n; j++) dp[i][j] = INF; //dp[i][j]表示走到点i经过j个点(不包括终点i)的时间 dp[1][0] = 0; while(!q.empty()) { int now = q.front(); q.pop(); for(int i = 0; i < (int)g[now].size(); i++) { int to = g[now][i].to; int dis = g[now][i].dis; for(int j = 1; j < n; j++) // { if(dp[now][j - 1] + dis < dp[to][j]) { dp[to][j] = dp[now][j - 1] + dis; pre[to][j] = now; } } } } int max_num = 0; for(int i = 0; i < n; i++) { if(dp[n][i] <= T) { max_num = i; } } cout << max_num + 1<< endl; //因为dp表示的是经过的点,所以终点需+1 int num = max_num; int cur = n; stack<int> st; while(cur != 1) //存路径 { st.push(cur); cur = pre[cur][num]; num = num - 1; } cout << "1" << " "; while(!st.empty()) { cout << st.top() << " "; st.pop(); } return 0; }
posted on 2019-05-23 21:45 stagelovepig 阅读(511) 评论(0) 编辑 收藏 举报