PKU Ubiquitous Religions(并查集)

 

http://acm.pku.edu.cn/JudgeOnline/problem?id=2524

 

题目大意:在大学里假设每个学生都有各自自己不同的信仰,现在题目给你成对出现的数据,标志着这两个人信仰是一样的,现在你要做个调查,调查下学校里到底有多少种不同的宗教信仰。

 

解题思路:并查集做,因为数据量太大了。

 

#include <stdio.h> #define size 50001 int parent[size]; int deep[size]; void CreateSet(int x) { parent[x] = x; deep[x] = 0; } int Find(int x) { int r; int temp; r = x; while (r!=parent[r]) r = parent[r]; while (x!=r) { temp = parent[x]; parent[x] = r; x = temp; } return r; } void Union(int a,int b) { int t1 = Find(a); int t2 = Find(b); if(deep[t1]>deep[t2]) parent[t2] = t1; else parent[t1] = t2; if(deep[t1]==deep[t2]) deep[t2]++; } int main() { int people,religion; int i; int a,b; int count; int t=1; while (scanf("%d%d",&people,&religion)!=EOF) { if(people==0&&religion==0) break; count = 0; for(i=1;i<=people;i++) CreateSet(i); while (religion--) { scanf("%d%d",&a,&b); if(Find(a)!=Find(b)) Union(a,b); } for (i=1;i<=people;i++) { if(parent[i] == i) count++; } printf("Case %d: %d/n",t,count); t++; } return 0; }

你可能感兴趣的:(PKU Ubiquitous Religions(并查集))