您的位置:首页 > 其它

HDU - 1213 How Many Tables (简单并查集)

2014-07-16 20:50 429 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1213

题意:

T组数据, 1~n个数,m对关系,开始每个数一个组,每个组间出现关系边,则合并这两个组,求最后剩余组数

分析:

二维邻接矩阵搜索可以实现,但效率较低,开销较大

直接运用并查集,查找、合并,最后求并查集的根节点数

核心:

int Find(int x)
{
if(x == parent[x])
return x;
else
return parent[x] = find(parent[x]);
}


代码:

#include <stdio.h>

int nt, father[10000];
int find(int x)
{
if(father[x]!=x)
father[x]=find(father[x]);
return father[x];
}
int main()
{
//int father[10000];
int t;
scanf("%d", &t);
while(t--)
{
int n, m, i, j, x, y, a, b;
scanf("%d%d", &n, &m);
nt=n;
for(i=1; i<=n;  i++)
{
father[i]=i;
}
for(i=0; i<m; i++)
{
scanf("%d%d", &x, &y);
a=find(x); b=find(y);
father[a]=b;
if(a!=b) nt--;
}
printf("%d\n", nt);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: