Kosaraju algorithm
See the Challenge Program Design Competition (P320)
Template:
Const intn=1e5+5;intN,m;vector<int>G[n];vector<int>Rg[n];vector<int>vs;BOOLVis[n];intCmp[n];voidAdd_edge (intUintv) {G[U].PB (v); RG[V].PB (u);} voidDfsintu) {Vis[u]=true; for(intI=0; I<g[u].size (); i++) if(!Vis[g[u][i]]) DFS (g[u][i]); VS.PB (u);}voidRdfsintUintk) {Vis[u]=true; Cmp[u]=K; for(intI=0; I<rg[u].size (); i++) if(!Vis[rg[u][i]]) Rdfs (rg[u][i],k);}intSCC () {mem (Vis,false); Vs.clear (); for(intI=1; i<=n;i++)if(!Vis[i]) DFS (i); Mem (Vis,false); intk=0; for(intI=vs.size ()-1; i>=0; i--)if(!vis[vs[i]]) Rdfs (vs[i],k++); returnK;}
Example 1:poj 2186 Popular cows
Code:
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<vector>using namespacestd;#definell Long Long#definePB Push_back#defineMem (A, B) memset (A,b,sizeof (a))Const intn=1e5+5;intN,m;vector<int>G[n];vector<int>Rg[n];vector<int>vs;BOOLVis[n];intCmp[n];voidAdd_edge (intUintv) {G[U].PB (v); RG[V].PB (u);} voidDfsintu) {Vis[u]=true; for(intI=0; I<g[u].size (); i++) if(!Vis[g[u][i]]) DFS (g[u][i]); VS.PB (u);}voidRdfsintUintk) {Vis[u]=true; Cmp[u]=K; for(intI=0; I<rg[u].size (); i++) if(!Vis[rg[u][i]]) Rdfs (rg[u][i],k);}intSCC () {mem (Vis,false); Vs.clear (); for(intI=1; i<=n;i++)if(!Vis[i]) DFS (i); Mem (Vis,false); intk=0; for(intI=vs.size ()-1; i>=0; i--)if(!vis[vs[i]]) Rdfs (vs[i],k++); returnK;}intMain () {Ios::sync_with_stdio (false); Cin.tie (0); CIN>>n>>m; intu,v; for(intI=0; i<m;i++) cin>>u>>V,add_edge (U,V); intt=SCC (); intans=0; for(intI=1; i<=n;i++)if(cmp[i]==t-1) ans++,u=i; Mem (Vis,false); Rdfs (U,0); for(intI=1; i<=n;i++)if(!vis[i]) ans=0; cout<<ans<<Endl; return 0;}
View Code
Example 2:
Algorithm note--strong connected component decomposition