朋友圈问题(并查集)
来源:互联网 发布:淘宝助理ipad版 编辑:程序博客网 时间:2024/05/21 21:37
问题描述:
假如已知有n个人和m对好友关系(存于数字r)。如果两个人是直接或间接的好友(好友的好友的好友...),则认为他们属于同一个朋友圈,请写出程序求出这n个人里一共有多少朋友圈。
例如:n=5,m=3,r={{1,2},{2,3},{4,5}},表示有5个人,1和2是好友,2和3是好友,4和5是好友。则1,2,3属于一个朋友圈,4,5属于另一个朋友圈,结果为两个朋友圈。
根据问题:我们可以用数据结构里的并查集来解决此问题。
问题解决:
#include <iostream>using namespace std;class UnionSet{public:UnionSet(int n):a(new int[n]){/*int* a=new int[n];*/for(int i=0;i<n;i++){a[i]=-1;}}~UnionSet(){if(a != NULL)delete a;}int FindRoot(int x){int root=x;while(a[root] >= 0){root--;/*root=a[root];*/}return root;}void Union(int root1,int root2){int _root1=FindRoot(root1);int _root2=FindRoot(root2);if(root1 != root2){a[_root1]+=a[_root2]; a[_root2]=_root1;}}int count(int n){int count=0;for(int i=0;i<n;i++){if(a[i] < 0)count++;}return count-1;}private:int *a;};int Friends(int n,int m,int r[][2]) //int *r[] {UnionSet u(n+1);for(int i=0;i<m;i++){u.Union(r[i][0],r[i][1]);}return u.count(n+1);}
8 4
- 朋友圈问题(并查集)
- 查并集(朋友圈问题)
- 朋友圈 (并查集)
- 图—并查集(解决朋友圈问题)
- 并查集-UnionSet【朋友圈问题】
- 小米面试题---朋友圈问题(并查集)
- 并查集解决朋友圈问题
- 并查集解决朋友圈问题
- 并查集/朋友圈
- 并查集(朋友圈)
- 并查集-朋友圈
- PAT 朋友圈(并查集)
- 5-9 朋友圈 (并查集)
- 奇怪的朋友圈(并查集)
- PAT--朋友圈--并查集
- 小米:朋友圈,并查集
- 【小米笔试题】朋友圈问题-并查集解法
- PTA 朋友圈【并查集的合并问题】
- SSD: Single Shot MultiBox Detector in TensorFlow(翻译)
- ubuntu下 google gmock使用
- Composer移除依赖
- 在Kali Linux 2016.2下安装Discuz需要安装php5.6
- uva156
- 朋友圈问题(并查集)
- HTML的一些常用标签
- 矩阵范数优化
- POJ 2291 Rotten Ropes G++
- 设定html table 过宽下方出现滚动条
- 在java独立进程(standalone app)中嵌入hawtio监控
- (转)Android WebView使用详解
- PHP使用redis防止大并发下二次写入
- 我是一个骄傲的人