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

UVALive 6091 并查集简单应用

时间:2016-05-30 15:22:44      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

点击打开链接

题意:问你给出的图中有多少颗树,树的定义与最小生成树类似,不能有重边或者环

思路:直接用并查集统计一下当前集合里的边的数量以及点的数量,如果点的数量与边的数量相等,那么是一颗树,统计完即可,水题~~~

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const ll INF=0x3f3f3f3f3f3f3f3fll;
const int maxn=510;
int f[maxn],num[maxn],r[maxn];
int find1(int x){
    if(x!=f[x]) f[x]=find1(f[x]);
    return f[x];
}
void unite(int a,int b){
    int aa=find1(a);
    int bb=find1(b);
    if(aa==bb){
        num[bb]++;return ;
    }
    f[aa]=bb;num[bb]+=num[aa];r[bb]+=r[aa];
}
int main(){
    int n,m,u,v,cas=1;
    while(scanf("%d%d",&n,&m)!=-1){
        if(n==0&&m==0) break;
        for(int i=0;i<=n;i++){
            f[i]=i;num[i]=1;r[i]=1;
        }
        for(int i=0;i<m;i++){
            scanf("%d%d",&u,&v);
            unite(u,v);
        }
        int sum=0;
        for(int i=1;i<=n;i++){
            if(find1(i)==i){
                if(r[i]==num[i]) sum++;
            }
        }
        if(sum==0) printf("Case %d: No trees.\n",cas++);
        else if(sum==1) printf("Case %d: There is one tree.\n",cas++);
        else printf("Case %d: A forest of %d trees.\n",cas++,sum);
    }
    return 0;
}

UVALive 6091 并查集简单应用

标签:

原文地址:http://blog.csdn.net/dan__ge/article/details/51526528

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