-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBOJ_1889.java
More file actions
83 lines (70 loc) · 2.17 KB
/
Copy pathBOJ_1889.java
File metadata and controls
83 lines (70 loc) · 2.17 KB
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
// BOJ - 1889
// Problem Sheet - https://www.acmicpc.net/problem/1889
import java.util.*;
import java.io.*;
public class Main {
private static int n;
private static int[] indegree;
private static boolean[] isVisit;
private static List<Integer>[] al;
private static PriorityQueue<Integer> pq;
public static void main(String[] args) throws IOException {
setup();
topologicalSort();
System.out.println(getResultStr());
}
private static void setup() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
n = Integer.parseInt(br.readLine());
al = new List[n + 1];
isVisit = new boolean[n + 1];
indegree = new int[n + 1];
pq = new PriorityQueue<>();
for(int i=1 ; i<=n ; i++) {
al[i] = new LinkedList<>();
}
for(int i=1 ; i<=n ; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
al[i].add(a);
al[i].add(b);
indegree[a]++;
indegree[b]++;
}
for(int i=1 ; i<=n ; i++) {
if(indegree[i] < 2) {
pq.add(i);
}
}
br.close();
}
private static void topologicalSort() {
while(!pq.isEmpty()) {
int cur = pq.poll();
if(isVisit[cur]) continue;
isVisit[cur] = true;
for(int next : al[cur]) {
indegree[next]--;
if(indegree[next] < 2) {
pq.add(next);
}
}
}
}
private static String getResultStr() {
StringBuilder sb = new StringBuilder();
List<Integer> participants = new LinkedList<>();
for(int i=1 ; i<=n ; i++) {
if(indegree[i] == 2) {
participants.add(i);
}
}
sb.append(participants.size()).append("\n");
for(int participant : participants) {
sb.append(participant).append(" ");
}
return sb.toString();
}
}