알고리즘 문제/BOJ
2150번 Strongly Connected Component
parkit
2019. 6. 2. 21:32
728x90
반응형
https://www.acmicpc.net/problem/2150
scc(강한 연결 요소) 문제이다.
익숙해지도록 복습하고, 다시 풀어보자.
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 | #include <bits/stdc++.h> using namespace std; #define Max 10001 int id, n[Max]; bool visit[Max]; vector<int> v[Max]; vector<vector<int> > scc; stack<int> s; int dfs(int start) { n[start] = ++id; s.push(start); int parent = n[start]; for (auto i : v[start]) { int next = i; if (n[next] == 0) parent = min(parent, dfs(next)); else if (!visit[next]) parent = min(parent, n[next]); } if (parent == n[start]) { vector<int> SCC; while (1) { int t = s.top(); s.pop(); visit[t] = true; SCC.push_back(t); if (t == start) break; } sort(SCC.begin(), SCC.end()); scc.push_back(SCC); } return parent; } int main(void) { int V, E, from, to; scanf("%d %d", &V, &E); while (E--) { scanf("%d %d", &from, &to); v[from].push_back(to); } for (int i = 1; i <= V; i++) if (!visit[i]) dfs(i); sort(scc.begin(), scc.end()); printf("%d\n", scc.size()); for (int i = 0; i < scc.size(); i++) { for (auto j : scc[i]) printf("%d ", j); printf("-1\n"); } return 0; } | cs |
728x90
반응형