输入一个有向图,计算每个节点所在强连通分量的编号,输出强连通分量的个数
1 #include<iostream> 2 #include<cstring> 3 #include<vector> 4 using namespace std; 5 const int maxn=1024; 6 struct Edge{ 7 int go,next; 8 }; 9 int vis[maxn],count=0,book[maxn]; 10 vector<Edge> G,G2; 11 vector<int> S; 12 int end[maxn],end2[maxn]; 13 void add(int from,int to){Edge e;e.go=to;e.next=end[from];G.push_back(e);end[from]=G.size()-1;} 14 void add2(int from,int to){Edge e;e.go=to;e.next=end2[from];G2.push_back(e);end2[from]=G2.size()-1;} 15 void dfs(int u) 16 { 17 vis[u]=1; 18 for(int i=end[u];i;i=G[i].next){ 19 int go=G[i].go; 20 if(!vis[go]) dfs(go); 21 } 22 S.push_back(u); 23 } 24 void dfs2(int u) 25 { 26 book[u]=count; 27 for(int i=end2[u];i;i=G2[i].next){ 28 int go=G2[i].go; 29 if(!book[go]) dfs2(go); 30 } 31 } 32 void init() 33 { 34 memset(vis,0,sizeof(vis)); 35 memset(end,0,sizeof(end)); 36 memset(end2,0,sizeof(end2)); 37 memset(book,0,sizeof(book)); 38 } 39 int main() 40 { 41 int n,m,a,b; 42 scanf("%d %d",&n,&m); 43 init(); 44 for(int i=1;i<=m;i++) 45 { 46 scanf("%d %d",&a,&b); 47 add(a,b); 48 add2(b,a); 49 } 50 for(int i=1;i<=n;i++) if(!vis[i]) dfs(i); 51 for(int i=n-1;i>=0;i--) if(!book[S[i]]){ 52 count++; 53 dfs2(S[i]); 54 } 55 cout<<count; 56 return 0; 57 }
时间: 2024-12-10 23:04:29