算法第五节(第4部分: 并查集)

本文详细介绍了一种高效的数据结构——并查集的实现方法,包括初始化、查找、合并等核心操作,通过C++代码展示了如何使用并查集解决集合间的关系判断问题。
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <queue>
#include <string>
#include <map>
using namespace std;
//
//  test.h
//  test
//
//  Created by 吴珝君 on 2018/12/31.
//  Copyright  ©   2018年 闲着也是贤者. All rights reserved.
//
/************************************************************************/
/************************************************************************/
/* 
并查集的实现
*/
/************************************************************************/


class UionFind
{
public:
	
	//初始化并查集
	void makeSet(  vector<string> v)
	{
		fatherMap.clear();
		sizeMap.clear();
	  for (int i = 0 ; i != v.size(); i++)
		{
			fatherMap.insert(map<string,  string> :: value_type(v[i],v[i]));
			sizeMap.insert(pair<string, int>(v[i], 1));
		}
	}
	
	public:
	//查找集合代表 :通常是根 并且实现路径压缩
	
	string findHead(string node)
	{
		if (fatherMap.count(node)>0)
		{
			string  father= fatherMap.find(node)->second;
			if (father != node)
			{
				father = findHead(father);
			}
			fatherMap.insert(pair<string,string>(node,father));
			return father;
		}
	return "";
	}
	bool isSameSet(string a, string b)
	{
		return  findHead(a) == findHead(b);

	}
	void Unions(string a, string b)
	{
		string n1 =  findHead(a);
		string n2 = findHead(b);
		if (n1 != n2)
		{
			int asize =  sizeMap.find(n1)->second;
			int bsize =  sizeMap.find(n2)->second;
			if (asize <= bsize)
			{
				fatherMap.insert(pair<string, string>(n1, n2));
				sizeMap.insert(pair<string, int>(n2, asize + bsize));//只保存了代表节点的大小
			}
			else
			{
				fatherMap.insert(pair<string, string>(n2, n1));
				sizeMap.insert(pair<string, int>(n1, asize + bsize));
			}
		}


	}
	

private:
	//存储元素个数
	map<string, string> fatherMap;//记录当前集合的父亲节点
	map<string, int>	sizeMap;//记录当前集合的元素个数

};

int main()
{
	vector<string> v;
	v.push_back("A");
	v.push_back("B");
	v.push_back("C");
	v.push_back("D");
	v.push_back("E");
		v.push_back("F");
	UionFind u ;
	u.makeSet(v);

	cout << u.isSameSet("A","B");
	u.Unions("A","B");
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值