Data Structures (Weiss) Chapter 8: Union and Find, Disjoint Sets, union by sizes, C++

本文介绍了一种使用 C++ 实现并查集的方法,该方法通过按大小合并集合来优化并查集的性能。文章详细展示了如何创建并查集类,并提供了 find 和 unionSets 方法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//

//  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;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值