现在的位置: 首页 > 综合 > 正文

hdu 1213

2013年05月10日 ⁄ 综合 ⁄ 共 718字 ⁄ 字号 评论关闭

这其实就是并查序的简单题目,看可以构建多少个数而已

URL :http://acm.hdu.edu.cn/showproblem.php?pid=1213

在判断有几个桌子的时候,我们一般的都是在合并完成后扫描整个父亲数组,发现几个father[i]==i,就判断有多少个树,从而需要多少个桌子

这只是个模板题,没什么说的,看代码

#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
using namespace std;
int father[1010];
int getfather(int n)
{
    while(n!=father[n])
       n=father[n];
    return n;
}
void Union(int x,int y)
{
    int rootx=getfather(x);
    int rooty=getfather(y);
    if(rootx!=rooty)
       father[rooty]=rootx;
}
void inti(int n)
{
    for(int i=1;i<=n;i++)
      father[i]=i;
}
int main()
{
    int N,m,n,i;
     scanf("%d",&N);
       while(N--)
       {
          scanf("%d%d",&n,&m);
           inti(n);
           int a,b;
          for(i=1;i<=m;i++)
          {
              scanf("%d%d",&a,&b);
              Union(a,b);
          }
          int c=0;
          for(i=1;i<=n;i++)
            if(father[i]==i)
               c++;
          printf("%d\n",c);
          getchar();  //  这一步比较关键,我开始一直没注意到,无线wa,坑爹啊。
        }
    return 0;
}

抱歉!评论已关闭.