Advertisement
istinishat

Strongly Connected Component

May 16th, 2017
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define si(n) scanf("%d",&n)
  5. #define MAX 100005
  6.  
  7. bool vis[MAX];
  8. vector<int>temp;
  9. vector<int>graph[MAX],rev_graph[MAX];
  10.  
  11. void dfs(int now)
  12. {
  13.     if(vis[now])
  14.         return;
  15.     vis[now]=true;
  16.  
  17.     for(int i=0;i<graph[now].size();i++){
  18.         dfs(graph[now][i]);
  19.     }
  20.     temp.push_back(now);
  21. }
  22.  
  23. void rev_dfs(int now){
  24.     if(vis[now])
  25.         return ;
  26.     vis[now]=true;
  27.     for(int i=0;i<rev_graph[now].size();i++)
  28.         rev_dfs(rev_graph[now][i]);
  29. }
  30.  
  31. int main()
  32. {
  33.     //freopen("input.txt","r",stdin);
  34.     int i,n,m,scc=0;
  35.     si(n);si(m);
  36.  
  37.     for(i=0;i<m;i++){
  38.         int u,v;
  39.         si(u);si(v);
  40.         graph[u].push_back(v);
  41.         rev_graph[v].push_back(u);
  42.     }
  43.  
  44.     memset(vis,false,sizeof(vis));
  45.     for(i=1;i<=n;i++){
  46.         if(!vis[i])dfs(i);
  47.     }
  48.     memset(vis,false,sizeof(vis));
  49.  
  50.     for(i=temp.size()-1;i>=0;i--){
  51.         int now=temp[i];
  52.         if(vis[now])
  53.             continue;
  54.         rev_dfs(now);
  55.         scc++;
  56.     }
  57.  
  58.     printf("total scc = %d",scc);
  59.  
  60.     return 0;
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement