Today is and check set of special, oh, test instructions not much explanation, can not understand to fill English bar sunglass (▔,▔) Deny, bare and check set, the first initialization let each point of the root node for himself, if the input a, B to know then put a A, a and a group of the same set (that is, let a, b root node, And the collection in the set with a point as the root node to represent this set, also known as the representative of the yuan, and finally as long as the detection of a few representatives of the yuan can know at least a few tables, there is a bit of the path compression, we find a bit of the root node from his parent node, Grandpa node What the past more annoying AH If this path is a long one, it's much more annoying to find it, so it's convenient to have each point on his path connected directly to the root node when we first look it up. Here's the code.
#include <bits/stdc++.h>
using namespace std;
int per[1005];
int sf (int x) {
int r=x;
while (R!=per[r]) {
r=per[r];
}
while (r!=x) {
int t=per[x];
Per[x]=r;
x=t;
}
return r;
}
void Union (int a,int b) {
if (SF (a)!=sf (b))
PER[SF (a)]=sf (b);
}
int main () {
int t,n,m,i,sum,a,b;
cin>>t;
while (t--) {
cin>>n>>m;
sum=0;
for (i=1;i<=n;i++)
per[i]=i;
for (i=1;i<=m;i++) {
cin>>a>>b;
Union (A, b);
}
for (i=1;i<=n;i++)
if (per[i]==i)
sum++;
cout<<sum<<endl;
}
return 0;
}
Ladies and gentlemen, are you crossing for getting started?