-
Notifications
You must be signed in to change notification settings - Fork 0
/
줄 세우기.java
65 lines (48 loc) · 1.54 KB
/
줄 세우기.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
import java.io.*;
import java.util.*;
public class Main {
static ArrayList<Integer> A[];
static boolean[] visited;
static int N,M;
static int[] count;
static StringBuilder sb;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
A= new ArrayList[N+1];
count = new int[N+1];
for(int i =1; i<=N; i++){
A[i] = new ArrayList<>();
}
visited= new boolean[N+1];
for(int i =0; i<M; i++) {
st = new StringTokenizer(br.readLine());
int S = Integer.parseInt(st.nextToken());
int E = Integer.parseInt(st.nextToken());
A[S].add(E);
count[E]++;
}
sb= new StringBuilder();
bfs();
System.out.println(sb);
}
static void bfs() {
Queue<Integer> queue = new LinkedList<>();
for(int i =1; i<=N; i++) {
if(count[i]==0)
queue.add(i);
}
while(!queue.isEmpty()) {
int cur = queue.poll();
sb.append(cur).append(" ");
for(int next: A[cur]) {
count[next]--;
if(count[next]==0) {
queue.add(next);
}
}
}
}
}