码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1213 并查集 水

时间:2014-10-05 03:47:37      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   os   for   sp   c   on   

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

做到一道网赛题 2-sat可写 貌似并查集也可写  但是并查集做法没想到 先水几道并查集重新理解下然后再去做

学到的就一点  Father数组中有些值一直保持最初的father[x] == x  最终集合的个数可以通过这个判断

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;

const int MAXN = 1000+100;

int n,m;
int father[MAXN];

int Find(int x)
{
    if(x!=father[x]) father[x]=Find(father[x]);
    return father[x];
}

void un(int x,int y)
{
    x=Find(x);
    y=Find(y);
    if(x!=y)father[x]=y;
}

int main()
{
    int ncase;
    scanf("%d",&ncase);
    while(ncase--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0;i<=n;i++)father[i]=i;
        int u,v;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&u,&v);
            un(u,v);
        }
        int ans=0;
        for(int i=1;i<=n;i++)
            if(i==father[i])ans++;
        printf("%d\n",ans);
    }
    return 0;
}


hdu 1213 并查集 水

标签:style   http   color   io   os   for   sp   c   on   

原文地址:http://blog.csdn.net/u011026968/article/details/39791599

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!