#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;
}