https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
1 struct pointtype 2 { 3 vector<int> next; 4 int col; 5 int lowlink; 6 bool vis; 7 }point[10001]; 8 int n,m; 9 int color; 10 stack<int> st; 11 void init() 12 { 13 scanf("%d%d",&n,&m); 14 for(int i=1;i<=n;i++) 15 { 16 point[i].next.clear(); 17 point[i].col=0; 18 point[i].vis=false; 19 } 20 for(int i=1;i<=m;i++) 21 { 22 int x,y; 23 scanf("%d%d",&x,&y); 24 point[x].next.push_back(y); 25 } 26 color=0; 27 return; 28 } 29 void dfs(int x) 30 { 31 color+=1; 32 point[x].col=color; 33 point[x].lowlink=color; 34 st.push(x); 35 point[x].vis=true; 36 vector<int>::iterator it; 37 for(it=point[x].next.begin();it!=point[x].next.end();it++) 38 { 39 if(point[*it].col==0) 40 { 41 dfs(*it); 42 point[x].lowlink=min(point[x].lowlink,point[*it].lowlink); 43 } 44 else 45 { 46 if(point[*it].vis) 47 { 48 point[x].lowlink=min(point[x].lowlink,point[*it].col); 49 } 50 } 51 } 52 if(point[x].lowlink==point[x].col) 53 { 54 int tmp; 55 do 56 { 57 tmp=st.top(); 58 st.pop(); 59 point[tmp].vis=false; 60 point[tmp].col=point[x].col; 61 }while(tmp!=x); 62 } 63 return; 64 } 65 void tarjan() 66 { 67 for(int i=1;i<=n;i++) 68 { 69 if(point[i].col==0) 70 { 71 dfs(i); 72 } 73 } 74 return; 75 }