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

find 并查集

时间:2014-11-06 12:39:21      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   for   sp   div   on   

// find  并查集 
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int MAXN = 10000+10;
int f[MAXN]; 
int find(int x)
{
    if(f[x]==x)return f[x];
    return f[x] = find (f[x]);
}
int main()
{
    int m,n;
    scanf("%d%d",&m,&n);
    for(int i=1;i<=m;i++) f[i] = i; 
    for(int i=1;i<=n;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        x=find (x);
        y=find (y);
        if(x!=y)
        {
            f[x]=y;
        }
    }
    int ans=0;
    for(int i=1;i<=m;i++)
    {
        if(f[i]==i) ans++;
    }
    cout<<ans<<endl;
    return 0;
}

 

find 并查集

标签:style   blog   io   color   os   for   sp   div   on   

原文地址:http://www.cnblogs.com/coutendl/p/4078243.html

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