标签:hdu how many tables 1213 union_find
2 5 3 1 2 2 3 4 5 5 1 2 5
2 4
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int pre[1010];
int union_find(int node)
{
int leaf=node;
while(node!=pre[node])node=pre[node];
while(leaf!=node)
{
int t_p=pre[leaf];
pre[leaf]=node;
leaf=t_p;
}
return node;
}
int main(int argc, char *argv[])
{
// freopen("1213.in","r",stdin);
int T;//测试用例数量T(1<=T<=25)
int N,M;//N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other.(1<=N,M<=1000)
int a,b;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&N,&M);
memset(pre,0,sizeof(pre));
int total=N;
for(int i=1;i<=N;++i)
pre[i]=i;
while(M--)
{
scanf("%d %d",&a,&b);
int p=union_find(a);
int q=union_find(b);
if(p!=q){
pre[p]=q;
total--;
}
}
printf("%d\n",total);
}
return 0;
}
HDU 1213 How Many Tables (并查集)
标签:hdu how many tables 1213 union_find
原文地址:http://blog.csdn.net/wdkirchhoff/article/details/41726963