//
// main.cpp
// Data Structure TRY1
//
// Created by zr9558 on 6/7/13.
// Copyright (c) 2013 zr9558. All rights reserved.
//
// Data Structure C++, Weiss, P.319 Disjoint set class
// do the union of the set like the form {0,1,2,...,n} where n is an integer.
// union by sizes
#include <iostream>
using namespace std;
#include <vector>
class DisjSets
{
public:
DisjSets(int numElements);
int find( int x)const;
int find( int x);
void unionSets( int root1,int root2);
private:
vector<int> s;
};
DisjSets::DisjSets(int numElements): s(numElements)
{
for( int i=0; i<s.size(); ++i)
s[i]=-1;
}
intDisjSets::find( int x)const
{
if(s[x]<0)return x; // s[x]==-1 denotes, x is the root of the set.
elsereturn find(s[x]);// find the root of x
}
intDisjSets::find( int x)
{
if( s[x]<0)
return x;
else
return s[x]=find(s[x]);
}
// union by sizes
voidDisjSets::unionSets( int root1, int root2)
{
if( s[root1]>=s[root2])
{
s[root2]+=s[root1];
s[root1]=root2;
}
else
{
s[root1]+=s[root2];
s[root2]=root1;
}
}
int main()
{
return 0;
}
本文介绍了一种使用 C++ 实现并查集的方法,该方法通过按大小合并集合来优化并查集的性能。文章详细展示了如何创建并查集类,并提供了 find 和 unionSets 方法的具体实现。

被折叠的 条评论
为什么被折叠?



