Home BOJ. Strongly Connected Component (2150)
Post
Cancel

BOJ. Strongly Connected Component (2150)

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


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

public class Main {
	static BufferedReader br;
	static int[] parent;
	static boolean[] handled;
	static int idx;
	static ArrayList<ArrayList<Integer>> al;
	static Stack<Integer> stack;
	static ArrayList<ArrayList<Integer>> scc;
	public static void main(String[] args) throws IOException {
		al = new ArrayList<>();
		stack = new Stack<>();
		scc = new ArrayList<>();
		idx = 1;
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int[] arr = getArr();
		int v = arr[0], e = arr[1];
		parent = new int[v+1];
		handled = new boolean[v+1];
		for(int i = 0; i <= v; i++) al.add(new ArrayList<Integer>());

		for(int i = 0; i < e; i++) {
			arr = getArr();
			al.get(arr[0]).add(arr[1]);
		}

		for(int i = 1; i <= v; i++) {
			if(parent[i] == 0) dfs(i);
		}

		if(scc.size() > 1) scc.sort((l, r) -> l.get(0) - r.get(0));
		sb.append(scc.size()).append("\n");

		for(ArrayList<Integer> tmp: scc) {
			for(int ele: tmp) sb.append(ele + " ");
			sb.append(-1).append("\n");
		}
		print(sb);
	}

	static int dfs(int i) {
		int origVal;
		origVal = parent[i] = idx++;
		stack.push(i);

		for(int vertex : al.get(i)) {
			if(parent[vertex] == 0) parent[i] = Math.min(parent[i], dfs(vertex));
			else if(!handled[vertex]) parent[i] = Math.min(parent[i], parent[vertex]);
		}

		if(parent[i] == origVal) {
			ArrayList<Integer> al = new ArrayList<>();
			while(true) {
				int idx = stack.pop();
				handled[idx] = true;
				al.add(idx);
				if(idx == i) break;
			}
			if(al.size() > 1) al.sort((l, r) -> l - r);
			scc.add(al);
		}

		return parent[i];
	}

	static int toi(String s) { return Integer.parseInt(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.