Advanced data structures - disjoint-set

Disjoint-set is actually advanced data structures ... I always thought he was the underlying data structures to the ... (wait for the next! It actually is a data structure!)

This may be all of the advanced data structure, the simplest of the simple and brief. Data structure of the topic in July ... the so-called sustainable point of divide and conquer I have yet to see ... (back a cool).

 Theoretical concepts

Personally, I think disjoint-set this thing back up and really understanding much faster than you pull up ... with a bunch of useless theory ... not as good as you are so few lines of code back to reality ...

A formality. We can be seen as a collection of disjoint-set. Initial time, into a respective set of each element. In subsequent operations, supports several functions such as names mentioned:

Merge: The two sets into one set of

Query: Find the element where the collection

So if something has great transitive, then the disjoint-set is well worth considering weapon. What is not emphasized here ... follow the path compression board back it. We have to figure out if, on the other hand simulate what count.

Code

The first is the initialization

void Load(){
    for(int i=1;i<=n;i++){
        father[i]=i;
    }
}

Then check

void find(int x){
    if(x==fater[x]) return x;
    return father[x]=find(father[x]);
}

And finally

void Merge(int x,int y){
    father[finx(x)]=y;
}

And then there are disjoint-set model one sideband power. This model allows you to store some information for each node to some of the path between the root node. In the follow-up I'll open a example to explain.

Edge Weighted disjoint-set

Questions come!

fa [x] represents the number in front of the No. x battleship battleship

D [x] indicates the number x in front of the ship

size [x] denotes the size of the root set in the x

#include<iostream>
#include<cmath>
using namespace std;
const int MAXN=90000;
int T;
int x,y;
char Order;
int fa[MAXN];
int size[MAXN];
int d[MAXN];
void Load()
{
    for(int i=1; i<=30000; i++)
    {
        fa[i]=i;
        size[i]=1;
    }
}
int Find(int x)
{
    if(x==fa[x])
    {
        return x;
    }
    int root=Find(fa[x]);
    d[x]+=d[fa[x]];
    return fa[x]=root;
}
void merge(int x,int y)
{
    x=Find(x);
    y=Find(y);
    fa[x]=y;
    d[x]=size[y];
    size[y]+=size[x];
}
int main()
{
    cin>>T;
    Load();
    while(T--)
    {
        cin>>Order>>x>>y;
        if(Order=='M')
        {
            merge(x,y);
        }
        else
        {
            if(Find(x)==Find(y))
            {
                cout<<abs(d[x]-d[y])-1<<endl;
            }
            else
            {
                cout<<-1<<endl;
            }
        }
    }
}

Did not see the data range, the data range is blind open. In fact, only minor modifications to the template like, not to mention difficult.

 

Guess you like

Origin www.cnblogs.com/Uninstalllingyi/p/11232734.html