Graph’s Cycle Component
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 2112 Accepted Submission(s): 775
Problem Description
In graph theory, a cycle graph is an undirected graph that consists of a single cycle, or in other words, some number of vertices connected in a closed chain.
Now, you are given a graph where some vertices are connected to be components, can you figure out how many components are there in the graph and how many of those components are cycle graphs.
Two vertices belong to a same component if and only if those two vertices connect each other directly or indirectly.
Input
The input consists of multiply test cases.
The first line of each test case contains two integer, n (0 < n < 100000), m (0 <= m <= 300000), which are the number of vertices and the number of edges.
The next m lines, each line consists of two integers, u, v, which means there is an edge between u and v.
You can assume that there is no multiply edges and no loops.
The last test case is followed by two zeros, which means the end of input.
Output
For each test case, output the number of all the components and the number of components which are cycle graphs.
Sample Input
8 9 0 1 1 3 2 3 0 2 4 5 5 7 6 7 4 6 4 7 2 1 0 1 0 0
Sample Output
2 1 1 0
Author
[email protected]
Source
2010 ACM-ICPC Multi-University Training Contest(12)——Host
by WHU
Recommend
zhouzeyong | We have carefully selected several similar problems for you: 3559 3558 3563 3562 3561
ac代码
#include<stdio.h> #include<string.h> int pre[100010],dig[100010]; int n,m; /*int find(int x) { int r=x; while(r!=pre[r]) r=pre[r]; int j,k; j=x; while(j!=r) { k=pre[j]; pre[j]=r; j=k; } return r; }*/ int main() { while(scanf("%d%d",&n,&m)!=EOF,n||m) { //init(); //memset(dig,0,sizeof(dig)); int i,j; for(i=1;i<=n;i++) { pre[i]=i; dig[i]=0; } for(i=0;i<m;i++) { int u,v; scanf("%d%d",&u,&v); u++;v++; dig[u]++; dig[v]++; //memge(u,v); int fa=u; while(fa!=pre[fa]) fa=pre[fa]; int fb=v; while(fb!=pre[fb]) fb=pre[fb]; if(fa!=fb) { if(fa<fb) { pre[fb]=fa; } else pre[fa]=fb; } } int ans1=0,ans2=0; for(i=1;i<=n;i++) { if(pre[i]==i) { ans1++; } } for(i=1;i<=n;i++) { if(dig[i]!=2) { int fi=i; while(fi!=pre[fi]) { fi=pre[fi]; } pre[fi]=0;//设为-1会超时,,,,, } } for(i=1;i<=n;i++) { if(pre[i]==i) ans2++; } printf("%d %d\n",ans1,ans2); } }