-
(백준 2105번 SCC) (라이님 블로그 대회 알고리즘 따라잡기 22) SCC카테고리 없음 2024. 7. 3. 10:48
백준 2105번
https://www.acmicpc.net/problem/2150
나동빈님의 블로그글을 토대로 짜본 알고리즘이다.
#include <iostream> #include <vector> #include <stack> #include <algorithm> #include <cstring> using namespace std; constexpr int MAX = 10001; int V, E; int id = 0, disc[MAX]; bool finished[MAX]; vector<int> adj[MAX]; vector<vector<int>> sccs; stack<int> st; int dfs(int u) { disc[u] = ++id; int parent = disc[u]; st.push(u); for (int v : adj[u]) { if (disc[v] == 0) parent = min(parent, dfs(v)); if (!finished[v]) parent = min(parent, disc[v]); } if (disc[u] == parent) { vector<int> scc; while (true) { int t = st.top(); st.pop(); scc.push_back(t); finished[t] = true; if (t == u) break; } sort(scc.begin(), scc.end()); sccs.emplace_back(scc); } return parent; } bool operator<(const vector<int>& v1, const vector<int>& v2) { return v1[0] < v2[0]; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); memset(disc, 0, sizeof(disc)); memset(finished, 0, sizeof(finished)); cin >> V >> E; for (int i = 0; i < E; i++) { int from, to; cin >> from >> to; adj[from].push_back(to); } for (int i = 1; i <= V; i++) { if (disc[i] == 0) dfs(i); } sort(sccs.begin(), sccs.end()); cout <<sccs.size() << "\n"; for (vector<int> v : sccs) { for (vector<int>::iterator it = v.begin(); it < v.end(); it++) { cout << (*it) << " "; } cout << "-1\n"; } return 0; }
플래티넘은 이 정도 난이도구나..ㅠㅠ 더 열심히 공부해야겠다!!!!