用并查集求朋友圈数目

小米的一道面试题:

假如已知有n个人和m对好友关系,如果两个人是直接或者间接有好友关系,则认为他们属于同一个朋友圈。写程序判断里面有多少朋友圈。
例如:
n = 5, m = 3  r = {(1,2), (2, 3), (4, 5)}  1 2 3 是一个朋友圈, 4 5 是一个朋友圈。
所以输出是2


这道题用并查集来求解就非常容易了。关于并查集的内容,这篇文章写得非常好:

http://blog.csdn.net/dm_vincent/article/details/7655764#reply

根据这篇文章,写了一个求解方法,代码如下:

[cpp]  view plain  copy
  1. class UnionFind {  
  2. public:  
  3.     UnionFind(int n) : cnt(n)  
  4.     {  
  5.         id = new int[n];  
  6.         for (int i = 0; i < n; i++)  
  7.             id[i] = i;  
  8.   
  9.         size = new int[n];  
  10.         for (int i = 0; i < n; i++)  
  11.             size[i] = 1;  
  12.     }  
  13.       
  14.     ~UnionFind()  
  15.     {  
  16.         delete[] id;  
  17.         delete[] size;  
  18.     }  
  19.   
  20.     // 返回连通组的个数  
  21.     int count()  
  22.     {  
  23.         return cnt;  
  24.     }  
  25.   
  26.     // 查找一个节点属于哪个组  
  27.     int findSet(int a)  
  28.     {  
  29.         if (id[a] == a)  
  30.             return a;  
  31.         else  
  32.             return id[a] = findSet(id[a]);  // 查找的同时提高节点的高度  
  33.     }  
  34.   
  35.     bool isSameSet(int a, int b)  
  36.     {  
  37.         int x = findSet(a); // 查找a的组号  
  38.         int y = findSet(b); // 查找b的组号  
  39.   
  40.         return x == y;      // 判断组号是否相同  
  41.     }  
  42.   
  43.     void Union(int a, int b)  
  44.     {  
  45.         int x = findSet(a);  
  46.         int y = findSet(b);  
  47.   
  48.         if (x != y)  
  49.         {  
  50.             if (size[x] < size[y])  
  51.             {  
  52.                 id[x] = y;  
  53.                 size[y] += size[x];  
  54.             }  
  55.             else  
  56.             {  
  57.                 id[y] = x;  
  58.                 size[x] += size[y];  
  59.             }  
  60.   
  61.             cnt--;  // 合并后组的数量-1  
  62.         }  
  63.     }  
  64.   
  65. private:  
  66.     int *id;  
  67.     int *size;  
  68.     int cnt;  
  69. };  
  70.   
  71. int main()  
  72. {  
  73.     UnionFind friends(5);  
  74.   
  75.     friends.Union(0, 1);  
  76.     friends.Union(1, 2);  
  77.     friends.Union(3, 4);  
  78.   
  79.     cout << "朋友圈数目:" << friends.count() << endl;  
  80.   
  81.     system("pause");  
  82.     return 0;  
  83. }  

运行结果:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值