HDU-1213-How Many Tables [并查集]

来源:互联网 发布:财务报销流程软件 编辑:程序博客网 时间:2024/05/16 12:56

题目传送门


题意:
本着小伙伴的小伙伴就是小伙伴的原则,所有的认识的人都可以坐在一张桌子上,问需要准备多少张桌子。
思路:
每输入两个序号,就将其合并,最后遍历所有人,父节点为自身就ans++。

#include <algorithm>#include <iostream>#include <cstdlib>#include <cstring>#include <cstdio>using namespace std;int Father[1200];void init(){    for (int i = 1; i <= 1000; i++)        Father[i] = i;}int Find(int x){    while (Father[x]!=x)        x = Father[x];    return x;}int main(void){    //freopen("in.txt","r",stdin);    //freopen("out.txt","w",stdout);    int t;    scanf("%d", &t);    while (t--)    {        init();        int m,n;        scanf("%d %d", &m, &n);        while (n--)        {            int x,y;            scanf("%d %d", &x, &y);            x = Find(x);            y = Find(y);            Father[x] = y;        }        int ans = 0;        for (int i = 1; i <= m; i++)        {            if (Father[i]==i)                ans++;        }        printf("%d\n",ans);    }    return 0;}
原创粉丝点击