UVa:10583 Ubiquitous Religions

来源:互联网 发布:mac终端查看文件内容 编辑:程序博客网 时间:2024/05/18 00:17

并查集。最后要求输出合并之后集合的个数。

 

原本我是找到每个结点的祖先并统计个数这样来做的。这里说一种更为高端的做法。

 

技巧体现在find函数的写法上。

将每个集合初始化为-1.表明为根节点,查询时则返回自身。同时压缩路径。

最后只统计-1的个数即可。

 

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int father[50005]={0};int find(int x){    return father[x]<0?x:(father[x]=find(father[x]));}int main(){    int n,m,_case=0;    while(scanf("%d%d",&n,&m)&&!(!m&!n))    {        int u,v;        memset(father,-1,sizeof(father));        for(int i=0;i<m;++i)        {            scanf("%d%d",&u,&v);            if(find(u)!=find(v))            father[find(u)]=find(v);        }        printf("Case %d: %d\n",++_case,count(&father[1],&father[n+1],-1));    }    return 0;}