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.
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.
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 11 0
题意:找出无向图中有几个连通块,有几个环
思路:并查集判断有几个连通块,根据点的度数判断是否成环,环的要求则是一个连通块中每个点的度数都是2,找到度数不是2的点判断它属于呢个连通块,则这个连通块不是环
#include<stdio.h> #include<string.h> #include <iostream> using namespace std; int f[100010],a[100010],d[100010]; int getf(int v) { if(f[v]==v) return v; f[v]=getf(f[v]); return f[v]; } void merge(int u,int v) { int t1,t2; t1=getf(u); t2=getf(v); if(t1!=t2) f[t1]=t2; return; } int main() { int n,m,u,v; while(~scanf("%d%d",&n,&m)) { if(n==0&&m==0) break; int sum=0,num=0; for(int i=0; i<n; i++) f[i]=i,a[i]=0,d[i]=0; for(int i=0; i<m; i++) { scanf("%d%d",&u,&v); a[u]++; //统计度数 a[v]++; merge(u,v); } for(int i=0; i<n; i++) { if(f[i]==i) //有几个连通块 sum++; } num=sum; for(int i=0; i<n; i++) { if(a[i]!=2) { int s=getf(i); //度数不是2的点找它的根节点,看它属于呢个连通块 if(d[s]==0) { d[s]=1; //标记此连通块不是环 num--; } } } printf("%d %d\n",sum,num); } return 0; }