Ubiquitous Religions
Time limit 10000 ms Memory limit 65536 kB
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.
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
HintHuge input, scanf is recommended.
題解:給你n,m,然後給你m行a,b,表示a,b有共同的宗教信仰,求最大的宗教數量,(最大爲n)……
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<string>
#include<math.h>
#include<map>
#include<queue>
#include<stack>
#define INF 0x3f3f3f3f
#define ll __int64
#define For(i,a,b) for(int i=a;i<b;i++)
#define sf(a) scanf("%d",&a)
#define sfs(a) scanf("%s",a)
#define sff(a,b) scanf("%d%d",&a,&b)
#define sfff(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define pf(a) printf("%d\n",a)
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
#define maxn 105
#define maxv 10005
int pre[50005],x[50005];
int find(int x) // 查找根節點
{
int s=x;
while(s!=pre[s]) // 查找根節點
{
s=pre[s];
}
int i=x,j;
while(pre[i]!=s) //路徑壓縮,節省查詢時間
{
j=pre[i];
pre[i]=s;
i=j;
}
return s;
}
void join(int x,int y) // 判斷x,y是否擁有共同的宗教信仰,若有就不管了,若沒有,讓兩人的信仰相同
{
int xx=find(x);int yy=find(y);
if(xx!=yy)
pre[xx]=yy;
}
int main()
{
int n,M,flag=0;
while(~sff(n,M)&&(n||M))
{
flag++;
for(int i=1;i<=n;i++) // 初始化各點的根節點爲自己本身
pre[i]=i;
int a,b;
For(i,0,M)
{
sff(a,b);
join(a,b); // 處理數據
}
mem(x,0);
for(int i=1;i<=n;i++)
{
x[find(i)]=1; // 標記根節點
}
int s=0;
for(int i=1;i<=n;i++) // 記錄根節點的數目,即最大宗教的數量
if(x[i])
{
s++;
}
printf("Case %d: ",flag);
printf("%d\n",s);
}
}