朋友圈问题(并查集)
2017-04-01 19:50
176 查看
问题描述:
假如已知有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属于另一个朋友圈,结果为两个朋友圈。
根据问题:我们可以用数据结构里的并查集来解决此问题。
问题解决:
假如已知有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 ) { /*int* a=new int ;*/ 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); }
相关文章推荐
- 并查集-UnionSet【朋友圈问题】
- 小米面试题---朋友圈问题(并查集)
- 【小米笔试题】朋友圈问题-并查集解法
- 【数据结构】朋友圈问题的解决——并查集
- 并查集解决朋友圈问题
- 图—并查集(解决朋友圈问题)
- 并查集解决朋友圈问题
- 并查集解决朋友圈问题
- 【九度OJ】:1526 并查集 朋友圈问题
- 并查集实现解决小米面试题朋友圈问题
- A Bug's Life (并查集,同性恋问题,注意处理性别)
- 【枚举优化/离散化/并查集】染色问题
- 小米面试题 朋友圈 并查集
- NYOJ 38布线问题(并查集)(最小生成树Kruskal)
- 九度OJ题目 1526 朋友圈 并查集
- 暑假集训中期测试 Problem D: 装箱问题2 (并查集)
- 欧拉路/回路_并查集 NYOJ 42 一笔画问题
- 并查集-朋友问题
- 并查集解决图的相关问题
- 并查集判断图有无回路问题之hdu1272