Strongly Connected Component
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 82 83 84 85
| #include <bits/stdc++.h>
#define MAX_N 10001 #define ll long long #define vll vector<ll> #define all(a) begin(a), end(a) using namespace std;
ll n, e; vll adj[MAX_N], radj[MAX_N]; ll rep[MAX_N]; bool vis1[MAX_N], vis2[MAX_N]; vll st;
void dfs1(ll u) { vis1[u] = true; for(auto& v : adj[u]) { if(!vis1[v]) dfs1(v); } st.push_back(u); }
void dfs2(ll u, ll r) { rep[u] = r; vis2[u] = true; for(auto& v : radj[u]) { if(!vis2[v]) dfs2(v, r); } }
vector<vll> solve() { for(ll i = 1; i <= n; i++) { for(auto& v : adj[i]) radj[v].push_back(i); }
for(ll i = 1; i <= n; i++) { if(!vis1[i]) dfs1(i); }
while(!st.empty()) { ll u = st.back(); st.pop_back(); if(!vis2[u]) dfs2(u, u); }
unordered_map<ll, vll> scc; for(ll i = 1; i <= n; i++) scc[rep[i]].push_back(i);
map<ll, ll> mp; for(auto& [k, v] : scc) { sort(all(v)); mp[v[0]] = k; }
vector<vll> res;
for(auto& [k, v] : mp) { res.push_back(scc[v]); }
return res; }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> e; while(e--) { ll u, v; cin>>u>>v; adj[u].push_back(v); }
auto res = solve(); cout<<res.size()<<'\n'; for(auto& r : res) { for(auto& c : r) cout<<c<<' ';cout<<"-1\n"; } return 0; }
|