首页 > 其他 > 详细

并查集的应用

时间:2016-06-30 23:30:47      阅读:136      评论:0      收藏:0      [点我收藏+]
  • 定义

 并查集是一种树型的数据结构,用于处理一些不相交集合(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;
}

本文出自 “学习记录” 博客,请务必保留此出处http://10794428.blog.51cto.com/10784428/1794733

并查集的应用

原文:http://10794428.blog.51cto.com/10784428/1794733

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!