forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path9.cpp
71 lines (61 loc) Β· 1.98 KB
/
9.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>
using namespace std;
// λ
Έλμ κ°μ(V)
int v;
// λͺ¨λ λ
Έλμ λν μ§μ
μ°¨μλ 0μΌλ‘ μ΄κΈ°ν
int indegree[501];
// κ° λ
Έλμ μ°κ²°λ κ°μ μ 보λ₯Ό λ΄κΈ° μν μ°κ²° 리μ€νΈ μ΄κΈ°ν
vector<int> graph[501];
// κ° κ°μ μκ°μ 0μΌλ‘ μ΄κΈ°ν
int times[501];
// μμ μ λ ¬ ν¨μ
void topologySort() {
vector<int> result(501); // μκ³ λ¦¬μ¦ μν κ²°κ³Όλ₯Ό λ΄μ 리μ€νΈ
for (int i = 1; i <= v; i++) {
result[i] = times[i];
}
queue<int> q; // ν λΌμ΄λΈλ¬λ¦¬ μ¬μ©
// μ²μ μμν λλ μ§μ
μ°¨μκ° 0μΈ λ
Έλλ₯Ό νμ μ½μ
for (int i = 1; i <= v; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
// νκ° λΉ λκΉμ§ λ°λ³΅
while (!q.empty()) {
// νμμ μμ κΊΌλ΄κΈ°
int now = q.front();
q.pop();
// ν΄λΉ μμμ μ°κ²°λ λ
Έλλ€μ μ§μ
μ°¨μμμ 1 λΉΌκΈ°
for (int i = 0; i < graph[now].size(); i++) {
result[graph[now][i]] = max(result[graph[now][i]], result[now] + times[graph[now][i]]);
indegree[graph[now][i]] -= 1;
// μλ‘κ² μ§μ
μ°¨μκ° 0μ΄ λλ λ
Έλλ₯Ό νμ μ½μ
if (indegree[graph[now][i]] == 0) {
q.push(graph[now][i]);
}
}
}
// μμ μ λ ¬μ μνν κ²°κ³Ό μΆλ ₯
for (int i = 1; i <= v; i++) {
cout << result[i] << '\n';
}
}
int main(void) {
cin >> v;
// λ°©ν₯ κ·Έλνμ λͺ¨λ κ°μ μ 보λ₯Ό μ
λ ₯λ°κΈ°
for (int i = 1; i <= v; i++) {
// 첫 λ²μ§Έ μλ μκ° μ 보λ₯Ό λ΄κ³ μμ
int x;
cin >> x;
times[i] = x;
// ν΄λΉ κ°μλ₯Ό λ£κΈ° μν΄ λ¨Όμ λ€μ΄μΌ νλ κ°μλ€μ λ²νΈ μ
λ ₯
while (true) {
cin >> x;
if (x == -1) break;
indegree[i] += 1;
graph[x].push_back(i);
}
}
topologySort();
}