forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path5.cpp
111 lines (100 loc) Β· 3.48 KB
/
5.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <bits/stdc++.h>
using namespace std;
int testCase, n, m;
// λͺ¨λ λ
Έλμ λν μ§μ
μ°¨μλ 0μΌλ‘ μ΄κΈ°ν
int indegree[501];
// κ° λ
Έλμ μ°κ²°λ κ°μ μ 보λ₯Ό λ΄κΈ° μν λ°°μ΄ μ΄κΈ°ν
bool graph[501][501];
int main(void) {
cin >> testCase;
// ν
μ€νΈ μΌμ΄μ€(Test Case)λ§νΌ λ°λ³΅
for (int tc = 0; tc < testCase; tc++) {
fill(indegree, indegree + 501, 0);
for (int i = 0; i < 501; i++) {
fill(graph[i], graph[i] + 501, false);
}
cin >> n;
// μλ
μμ μ 보 μ
λ ₯
vector<int> v;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
v.push_back(x);
}
// λ°©ν₯ κ·Έλνμ κ°μ μ 보 μ΄κΈ°ν
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
graph[v[i]][v[j]] = true;
indegree[v[j]] += 1;
}
}
// μ¬ν΄ λ³κ²½λ μμ μ 보 μ
λ ₯
cin >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
// κ°μ μ λ°©ν₯ λ€μ§κΈ°
if (graph[a][b]) {
graph[a][b] = false;
graph[b][a] = true;
indegree[a] += 1;
indegree[b] -= 1;
}
else {
graph[a][b] = true;
graph[b][a] = false;
indegree[a] -= 1;
indegree[b] += 1;
}
}
// μμ μ λ ¬(Topology Sort) μμ
vector<int> result; // μκ³ λ¦¬μ¦ μν κ²°κ³Όλ₯Ό λ΄μ 리μ€νΈ
queue<int> q; // ν λΌμ΄λΈλ¬λ¦¬ μ¬μ©
// μ²μ μμν λλ μ§μ
μ°¨μκ° 0μΈ λ
Έλλ₯Ό νμ μ½μ
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
bool certain = true; // μμ μ λ ¬ κ²°κ³Όκ° μ€μ§ νλμΈμ§μ μ¬λΆ
bool cycle = false; // κ·Έλν λ΄ μ¬μ΄ν΄μ΄ μ‘΄μ¬νλμ§ μ¬λΆ
// μ νν λ
Έλμ κ°μλ§νΌ λ°λ³΅
for (int i = 0; i < n; i++) {
// νκ° λΉμ΄ μλ€λ©΄ μ¬μ΄ν΄μ΄ λ°μνλ€λ μλ―Έ
if (q.size() == 0) {
cycle = true;
break;
}
// νμ μμκ° 2κ° μ΄μμ΄λΌλ©΄ κ°λ₯ν μ λ ¬ κ²°κ³Όκ° μ¬λ¬ κ°λΌλ μλ―Έ
if (q.size() >= 2) {
certain = false;
break;
}
// νμμ μμ κΊΌλ΄κΈ°
int now = q.front();
q.pop();
result.push_back(now);
// ν΄λΉ μμμ μ°κ²°λ λ
Έλλ€μ μ§μ
μ°¨μμμ 1 λΉΌκΈ°
for (int j = 1; j <= n; j++) {
if (graph[now][j]) {
indegree[j] -= 1;
// μλ‘κ² μ§μ
μ°¨μκ° 0μ΄ λλ λ
Έλλ₯Ό νμ μ½μ
if (indegree[j] == 0) {
q.push(j);
}
}
}
}
// μ¬μ΄ν΄μ΄ λ°μνλ κ²½μ°(μΌκ΄μ±μ΄ μλ κ²½μ°)
if (cycle) cout << "IMPOSSIBLE" << '\n';
// μμ μ λ ¬ κ²°κ³Όκ° μ¬λ¬ κ°μΈ κ²½μ°
else if (!certain) cout << "?" << '\n';
// μμ μ λ ¬μ μνν κ²°κ³Ό μΆλ ₯
else {
for (int i = 0; i < result.size(); i++) {
cout << result[i] << ' ';
}
cout << '\n';
}
}
}