程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> POJ 2524 Ubiquitous Religions(並查集)

POJ 2524 Ubiquitous Religions(並查集)

編輯:關於C++
Ubiquitous Religions Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 25556 Accepted: 12619

Description

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 9
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
10 4
2 3
4 5
4 8
5 8
0 0

Sample Output

Case 1: 1
Case 2: 7

Hint

Huge input, scanf is recommended.
我看計劃的時候它是說分治,不過我一看這就是用並查集搞啊,我在懷疑是不是計劃上的分類弄錯了,然後我去網上看看博客,大家都是用並查集做的,也沒有什麼分治啊~ 知道用並查集,思路就很簡單了:初始化f[]數組,如果兩個人信仰的宗教一樣就把他們合並,最後遍歷f[]數組看看還有幾個沒合並的就是答案。(不過這裡到最後也可以不用遍歷f[]數組,可以在每合並一次,總學生數就n--,最後的n就是答案了,這樣應該可能會快一點吧~) 還有就是我這裡把m定義成了64位的,怕溢出,不知道這裡會不會爆int,沒試,大家如果知道的話可以給我評論說一下,謝謝啦~^_^
#include 
#include 
#include 
#define MAX 50000
typedef long long ll;

struct UFSet
{
	int f[MAX+2];
	int i;
	void init(int n){
		for(i=0;i<=n;i++)
			f[i]=i;
	}
	int find(int x){return f[x]==x?x:f[x]=find(f[x]);}
	void Union(int x,int y){
		if((x=find(x))==(y=find(y))) return ;
		f[y]=x;
	}
}S;

int main()
{
	int i,j,n,res,cas=1;
	ll m;
	int a,b;
	while(scanf("%d%lld",&n,&m)!=EOF)
	{
		if(n==0 && m==0)
			break;
		S.init(n);
		res=0;
		for(i=0;i

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved