定义
并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题。常常在使用中以森林来表示。
应用
若某个朋友圈过于庞大,要判断两个人是否是在一个朋友圈,确实还很不容易,给出某个朋友关系图,求任意给出的两个人是否在一个朋友圈。 规定:x和y是朋友,y和z是朋友,那么x和z在一个朋友圈。如果x,y是朋友,那么x的朋友都与y的在一个朋友圈,y的朋友也都与x在一个朋友圈。
如下图:
代码:
//找朋友圈个数
//找父亲节点
int FindRoot(int child1, int *_set)
{
int root = child1;
while (_set[root] >= 0)
{
root = _set[root];
}
return root;
}
//合并
void Union(int root1, int root2, int *&_set)
{
_set[root1] += _set[root2];
_set[root2] = root1;
}
int Friend(int n, int m, int r[][2])//n为人数,m为组数,r为关系
{
assert(n > 0);
assert(m > 0);
assert(r);
int *_set = new int[n];
for (int i = 0; i < n+1; i++)
{
_set[i] = -1;
}
for (int i = 0; i < m; i++)
{
int root1 = FindRoot(r[i][0],_set);
int root2 = FindRoot(r[i][1],_set);
if ((_set[root1] == -1 && _set[root2] == -1) || root1 != root2)
{
Union(root1, root2, _set);
}
}
int count = 0;
for (int i = 1; i <= n; i++)
{
if (_set[i] < 0)
{
count++;
}
}
return count;
}
//主函数
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<assert.h>
#include"UnionFindSet.h"
int main()
{
int r[][2] = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 5, 6 } };
cout << Friend(6, 4, r) << endl;
system("pause");
return 0;
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。