poj 2524Ubiquitous Religions (并查集)

来源:互联网 发布:ubuntu 脚本使用教程 编辑:程序博客网 时间:2024/06/05 00:56

题目描述:

世界上宗教何其多。假设你对自己学校的学生总共有多少种宗教信仰很感兴趣。学校有n个学生,但是你不能直接问学生的信仰,不然他会感到很不舒服的。有另外一个方法是问m对同学,是否信仰同一宗教。根据这些数据,相信聪明的你是能够计算学校最多有多少种宗教信仰的。(好,不罗嗦那么多了)

  解题思路---->显然并查集了。并查集的详细解释在可以点击 并查集(不相交集合)进行学习。思路可以很清晰的,一开始假设大家都各自信仰一个宗教,那么总的数目ans就是学生数目,每当发现有一对学生信仰同一个宗教,那么ans--;

There are so many different religions in the world today that it is difficult to keep track of them all. You are interested in finding out how many different religions students in your university believe in. 

You know that there are n students in your university (0 < n <= 50000). It is infeasible for you to ask every student their religious beliefs. Furthermore, many students are not comfortable expressing their beliefs. One way to avoid these problems is to ask m (0 <= m <= n(n-1)/2) pairs of students and ask them whether they believe in the same religion (e.g. they may know if they both attend the same church). From this data, you may not know what each person believes in, but you can get an idea of the upper bound of how many different religions can be possibly represented on campus. You may assume that each student subscribes to at most one religion.
Input
The input consists of a number of cases. Each case starts with a line specifying the integers n and m. The next m lines each consists of two integers i and j, specifying that students i and j believe in the same religion. The students are numbered 1 to n. The end of input is specified by a line in which n = m = 0.
Output
For each test case, print on a single line the case number (starting with 1) followed by the maximum number of different religions that the students in the university believe in.
Sample Input
10 91 21 31 41 51 61 71 81 91 1010 42 34 54 85 80 0
Sample Output
Case 1: 1Case 2: 7
Hint
Huge input, scanf is recommended.
AC代码:

#include <iostream>#include<cstdio>using namespace std;const int MAXN = 50005; /*结点数目上线*/int pa[MAXN];    /*p[x]表示x的父节点*/int ran[MAXN];    /*rank[x]是x的高度的一个上界*/int n, ans;void make_set(int x){/*创建一个单元集*/pa[x] = x;ran[x] = 0;}int find_set(int x){/*带路径压缩的查找*/if (x != pa[x])pa[x] = find_set(pa[x]);return pa[x];}/*按秩合并x,y所在的集合*/void union_set(int x, int y){x = find_set(x);y = find_set(y);if (x == y)return;ans--;    //统计if (ran[x] > ran[y])/*让rank比较高的作为父结点*/{pa[y] = x;}else{pa[x] = y;if (ran[x] == ran[y])ran[y]++;}}//answer to 2524int main(){int m, i, j = 1, x, y;while (scanf("%d%d", &n, &m)){if (n == m && m == 0) break;for (i = 1; i <= n; i++)make_set(i);ans = n;for (i = 0; i < m; i++){scanf("%d%d", &x, &y);union_set(x, y);}printf("Case %d: %d\n", j, ans);j++;}return 0;}


0 0
原创粉丝点击