Description
One day Stubird bought a transformer, the clerk said, this transformers and other kind of cheat children's different he really can deform. This transformer has n parts, they can connect with each other, make up the robot, of course, can also be deformed. But one day, the tesseract energy suddenly disappeared, parts scattered, of course, some parts are connected. Now that you have all the parts connected, he can get back to the original, for example, there are 4 parts, 3,4 is connected, and you just need to connect the 1 and the 3 (1,4 or 2,3 or 2,4) and he can get back to the original. He now asks you how many connections you need at least to get it back to the same place?
Input
The first line, a T, indicates that there is a T test sample next N and M (n<=10^5,0<=m<=10^5), n represents the number of parts, and M indicates how many parts are connected to the M line below, and each line u,v indicates that the part u,v is connected. (1<=u,v<=n)
Output
To find the minimum number of connections
Sample Input2 1 0 5 2 1 2 3 4Sample Output0 2HINT
Simple and Check Collection ~ ~ ~
Main and check set on three, establish find function, establish join function, P[i] Assignment
#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;Const intMAX =100100;intP[max],t[max];intFindintx) { returnx = = P[x]? X:P[X] =find (P[x]);}voidJoinintXinty) { intFX =find (x); intFY =find (y); if(fx!=fy) p[fx]=fy;}intMain () {intt,n,x,y,m; scanf ("%d",&T); while(t--) {memset (T,0,sizeof(t)); scanf ("%d%d",&n,&m); for(inti =1; I <= N; i++) P[i]=i; for(inti =1; I <= m; i++) {scanf ("%d%d",&x,&y); Join (x, y); } for(inti =1; I <= N; i++) T[find (i)]=1; intAns =0; for(inti =1; I <= N; i++) if(T[i]) ans++; printf ("%d\n", ans-1); } return 0;}
View Code
Guang Gong School race--and search--Transformers