forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path5.java
110 lines (99 loc) Β· 4.1 KB
/
5.java
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
import java.util.*;
public class Main {
public static int testCase, n, m;
// λͺ¨λ λ
Έλμ λν μ§μ
μ°¨μλ 0μΌλ‘ μ΄κΈ°ν
public static int[] indegree = new int[501];
// κ° λ
Έλμ μ°κ²°λ κ°μ μ 보λ₯Ό λ΄κΈ° μν λ°°μ΄ μ΄κΈ°ν
public static boolean[][] graph = new boolean[501][501];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
testCase = sc.nextInt();
for (int tc = 0; tc < testCase; tc++) {
Arrays.fill(indegree, 0);
for (int i = 0; i < 501; i++) {
Arrays.fill(graph[i], false);
}
n = sc.nextInt();
// μλ
μμ μ 보 μ
λ ₯
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
arrayList.add(x);
}
// λ°©ν₯ κ·Έλνμ κ°μ μ 보 μ΄κΈ°ν
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
graph[arrayList.get(i)][arrayList.get(j)] = true;
indegree[arrayList.get(j)] += 1;
}
}
// μ¬ν΄ λ³κ²½λ μμ μ 보 μ
λ ₯
m = sc.nextInt();
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
// κ°μ μ λ°©ν₯ λ€μ§κΈ°
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) μμ
ArrayList<Integer> result = new ArrayList<>(); // μκ³ λ¦¬μ¦ μν κ²°κ³Όλ₯Ό λ΄μ 리μ€νΈ
Queue<Integer> q = new LinkedList<>(); // ν λΌμ΄λΈλ¬λ¦¬ μ¬μ©
// μ²μ μμν λλ μ§μ
μ°¨μκ° 0μΈ λ
Έλλ₯Ό νμ μ½μ
for (int i = 1; i <= arrayList.size(); i++) {
if (indegree[i] == 0) {
q.offer(i);
}
}
boolean certain = true; // μμ μ λ ¬ κ²°κ³Όκ° μ€μ§ νλμΈμ§μ μ¬λΆ
boolean 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.poll();
result.add(now);
// ν΄λΉ μμμ μ°κ²°λ λ
Έλλ€μ μ§μ
μ°¨μμμ 1 λΉΌκΈ°
for (int j = 1; j <= n; j++) {
if (graph[now][j]) {
indegree[j] -= 1;
// μλ‘κ² μ§μ
μ°¨μκ° 0μ΄ λλ λ
Έλλ₯Ό νμ μ½μ
if (indegree[j] == 0) {
q.offer(j);
}
}
}
}
// μ¬μ΄ν΄μ΄ λ°μνλ κ²½μ°(μΌκ΄μ±μ΄ μλ κ²½μ°)
if (cycle) System.out.println("IMPOSSIBLE");
// μμ μ λ ¬ κ²°κ³Όκ° μ¬λ¬ κ°μΈ κ²½μ°
else if (!certain) System.out.println("?");
// μμ μ λ ¬μ μνν κ²°κ³Ό μΆλ ₯
else {
for (int i = 0; i < result.size(); i++) {
System.out.print(result.get(i) + " ");
}
System.out.println();
}
}
}
}