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 52 53 54 55 | #include <stdio.h> #include <queue> #include <vector> #include <algorithm> using namespace std; int cost[600] = { 0 }; int indegree[600] = { 0 }; int rst[600] = { 0 }; vector<vector<int> > adj(600); queue<int> q; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &cost[i]); while (1) { int num; scanf("%d", &num); if (num == -1) break; indegree[i]++; adj[num].push_back(i); } } for (int i = 1; i <= n; i++) if (indegree[i] == 0) { q.push(i); rst[i] = cost[i]; } while (q.empty() == false) { int x = q.front(); q.pop(); for (int i = 0; i < adj[x].size(); i++) { indegree[adj[x][i]]--; rst[adj[x][i]] = max(rst[adj[x][i]], rst[x]+cost[adj[x][i]]); if(indegree[adj[x][i]] == 0) q.push(adj[x][i]); } } for (int i = 1; i <= n; i++) printf("%d\n", rst[i]); } | cs |
'알고리즘 > 위상정렬' 카테고리의 다른 글
가장 멀리 떨어진 두 점 더블릿 (0) | 2019.03.12 |
---|---|
2252 줄세우기 (0) | 2019.03.09 |