poj 2524 Ubiquitous Religions(数据结构:并查集)

来源:互联网 发布:表白网站源码大全 编辑:程序博客网 时间:2024/05/05 04:11

题意是告诉你有n个学生,其中m对学生信仰相同

让你输出n个学生一共有多少个信仰

简单并查集的使用,学生信仰相同则并入相同集合

最后输出有多少个集合即可

注意数组大小,因为这个RE了一次可怜

代码如下:

#include <cstdio>#include <iostream>#include <algorithm>#define MAXN 50010#define LL long longusing namespace std;int p[MAXN], n, m;int find(int x) {    return p[x]==x ? x : p[x] = find(p[x]);}int cnt() {    int i, ans = 0;    for(i=0; i<n; ++i) {        if(p[i] == i)            ans++;    }    return ans;}int main(void) {    int a, b, i, res = 1;    while(scanf("%d%d", &n, &m) && (n+m)) {        for(i=1; i<=n; ++i)            p[i] = i;        while(m--) {            scanf("%d%d", &a, &b);            a = find(a);            b = find(b);            if(a != b)                p[a] = b;        }        printf("Case %d: %d\n", res++, cnt());    }    return 0;}


0 0
原创粉丝点击