Home BOJ. Workbook (1766)
Post
Cancel

BOJ. Workbook (1766)

[Link] https://www.acmicpc.net/problem/1766


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
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static StringBuilder sb = new StringBuilder();
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		int[] arr = getArr();
		int n = arr[0], m = arr[1];
		int[] deg = new int[n];
		boolean[] visit = new boolean[n];
		ArrayList<ArrayList<Integer>> edges = new ArrayList<>();
		for(int i = 0; i < n; i++) edges.add(new ArrayList<Integer>());

		for(int i = 0; i < m; i++) {
			arr = getArr();
			int a = arr[0] - 1, b = arr[1] - 1;
			edges.get(a).add(b);
			deg[b]++;
		}

		PriorityQueue<Integer> q = new PriorityQueue<>();

		for(int i = 0; i < n; i++) {
			if(visit[i]) continue;
			q.add(i);
			while(!q.isEmpty()) {
				int cur = q.poll();
				if(visit[cur] || deg[cur] != 0) continue;
				visit[cur] = true;
				sb.append(cur + 1).append(" ");
				for(int v: edges.get(cur)) {
					if(--deg[v] == 0) {
						q.add(v);
					}
				}
			}
		}

		print(sb);
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static long tol(String s) { return Long.parseLong(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.