POJ 2524 Ubiquitous Religions(并查集)

题目链接

赤裸裸的并查集,搞不懂为什么POJ计划里,会用分治做。。

 1 #include <stdio.h>

 2 #include <string.h>

 3 #define N 50001

 4 int o[N];

 5 int find(int x)

 6 {

 7     int r,t;

 8     r = x;

 9     while(x != o[x])

10     x = o[x];

11     while(r != x)

12     {

13         t = o[r];

14         o[r] = x;

15         r = t;

16     }

17     return x;

18 }

19 void merge(int x,int y)

20 {

21     x = find(x);

22     y = find(y);

23     if(x != y)

24     o[x] = y;

25 }

26 int main()

27 {

28     int n,m,i,sv,ev,num = 0,sum;

29     while(scanf("%d%d",&n,&m)!=EOF)

30     {

31         if(n == 0&&m == 0)break;

32         num ++;

33         for(i = 1;i <= n;i ++)

34         o[i] = i;

35         for(i = 1;i <= m;i ++)

36         {

37             scanf("%d%d",&sv,&ev);

38             merge(sv,ev);

39         }

40         printf("Case %d: ",num);

41         sum = 0;

42         for(i = 1;i <= n;i ++)

43         {

44             if(o[i] == i)

45             sum ++;

46         }

47         printf("%d\n",sum);

48     }

49     return 0;

50 }

你可能感兴趣的:(poj)