hdu1232 并查集

时间:2023-03-08 21:58:52

1、 hdu1232

2、链接:http://acm.hdu.edu.cn/showproblem.php?pid=1232

3、总结:简单并查集

#include<iostream>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
#include<cstdio>
using namespace std;
#define LL long long
#define INF 0x3f3f3f3f const int N=;
int father[N]; /* //未优化的查找
int findn(int n)
{
while(father[n]!=n){
n=father[n];
}
return n;
} */ int findn(int n)
{
int x=n;
while(father[x]!=x){
x=father[x];
} int i=n,j;
while(father[i]!=x) //优化
{
j=father[i];
father[i]=x;
i=j;
}
return x;
} int main()
{
int n,m;
while(scanf("%d",&n)!=EOF&&n)
{
//初始化
for(int i=;i<=n;i++)
father[i]=i; scanf("%d",&m);
int x,y;
for(int i=;i<m;i++)
{
scanf("%d%d",&x,&y); //合并
int tempx=findn(x);
int tempy=findn(y);
if(tempx!=tempy)father[tempx]=tempy; } //找出连通分量的个数,减一
int num=;
for(int i=;i<=n;i++)
{
if(father[i]==i)num++;
}
printf("%d\n",num-); } return ;
}