//并查集模板
//11.11.2015 by blacktea >>>>>_<<<<<
// this version isn't the best I will change it time by time
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#define LL long long
using namespace std;
int i,j,k,n,m,t,pre[1000000],rounte[100000],a,b;
void init()//初始化
{
memset(rounte,0,sizeof(rounte));
for(i=1;i<=n;i++)
pre[i] = i;
}
int toGetFarther(int x)//获得他们的祖宗
{
int x1 = x;
while(pre[x]!=x)x = pre[x];
if(pre[x1]!=x) pre[x1] = x;
return x;
}
void join(int x,int y)//判断他们是否是一个祖宗
{
x = toGetFarther(x);
y = toGetFarther(y);
if(x!=y)pre[x] = y;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
int sum = 0;
init();
while(m--)
{
scanf("%d%d",&a,&b);
join(a,b);
}
for(i=1;i<=n;i++)
{
int r = i;
while(pre[r]!=r)
r = pre[r];
rounte[r]++;
}
for(i=1;i<=n;i++)
if(rounte[i])sum++;//判断祖宗的个数即为有多少个独立的区间
printf("%d\n",sum);
}
return 0;
}
上面那个有点乱搞这个比较正统
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,l1,a,fa[200],am[200];
struct edge{
int x,y,v;
}e[20000];
void init()
{
for(int i=0;i<n;i++)
{
fa[i] = i;
am[i] = 1;
}
}
int findFarther(int x)
{
while(fa[x]!=x){
x = fa[x];
}
return x;
}
void Union(int x,int y)
{
int rootx = findFarther(x),rooty = findFarther(y);
if(rootx!=rooty){
if(am[rootx]>am[rooty]){
fa[rooty] = rootx;
am[rootx]+=am[rooty];
}
else{
fa[rootx] = rooty;
am[rooty]+=am[rootx];
}
}
}
void UnionFind()
{
for(int i=0;i<l1;i++)
{
Union(e[i].x,e[i].y);
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
init();
l1 = 0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
scanf("%d",&a);
e[l1].x = i;
e[l1].y = j;
e[l1].v = a;
l1++;
}
}
return 0;
}