Ubiquitous Religions--POJ 2524

1、解题思路:并查集。

2、注意事项:借用father[]、rank[]两个数组记录的小技巧。

3、实现方法:

 
  
1 #include < iostream >
2 #define M 50010
3 using namespace std;
4
5 int father[M],rank[M],ans;
6
7 void Makeset( int x)
8 {
9 father[x] = x;
10 rank[x] = 0 ;
11 }
12
13 int Findfather( int x)
14 {
15 if (x != father[x])
16 father[x] = Findfather(father[x]);
17 return father[x];
18 }
19
20 void Union( int x, int y)
21 {
22 int a = Findfather(x);
23 int b = Findfather(y);
24 if (a != b)
25 {
26 if (rank[a] > rank[b])
27 father[b] = a;
28 else
29 {
30 if (rank[a] == rank[b])
31 rank[b] ++ ;
32 father[a] = b;
33 }
34 ans -- ;
35 }
36 }
37
38 int main()
39 {
40 int i,j,n,m,tmp1,tmp2,cnt = 0 ;
41 while (cin >> n >> m)
42 {
43 if ( ! n && ! m)
44 break ;
45 for (j = 1 ;j <= n;j ++ )
46 Makeset(j);
47 ans = n;
48 for (i = 0 ;i < m;i ++ )
49 {
50 scanf( " %d %d " , & tmp1, & tmp2);
51 Union(tmp1,tmp2);
52 }
53 cout << " Case " <<++ cnt << " : " << ans << endl;
54 }
55 return 0 ;
56 }

 

 

 

转载于:https://www.cnblogs.com/yongze103/archive/2010/07/22/1783293.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值