Disjoint-set!!!

Disjoint-set of notes

(wtcl fat content such that only the cj)
disjoint-set, for solving the connectivity determination. At best it should be able to achieve log (n) level. This is much faster than the ah ah ah ah ah dfs and bfs.

Disjoint-set, as the name implies, it is divided into two:

Introduction general idea

With an id array, who represented his father Yes. As a result,
determine the connectivity problem is transformed into see their father is not one.
On the code:

typedef long long ll;
ll n,m,x,y,z,id[N];

merge

For example, the relationship between x and y Unicom.
That we might make y is the father of x.
So, id [x] = y; with these words can make a person easily become your son.
On the code:

void unite(ll x,ll y){
    ll xi=find(x),yi=find(y);
    id[xi]=yi;
}

Seek

We follow his father's son to find a relationship a go:
you're looking for x [i] father, is equivalent to find d [x [i]] dad always looking down, always to a end.
This man, is the father's father's father's father's father's father's father's father's father's father's father's father's father's father's father's father's father's father's father's father's father's father your father's father.
This person is looking for your ancestors
on the code:

ll find(ll x){
    if(id[x]==x)return x;
    return id[x]=find(id[x]);
}

Sentenced to communicate

Suppose there are two points: xi and yi
if you are connected, then xi is equal to my father's father y.

Overall template code section (so excited):

#include<iostream>
#define N 100010
using namespace std;
typedef long long ll;
ll n,m,x,y,z,id[N];
ll find(ll x){
    if(id[x]==x)return x;
    return id[x]=find(id[x]);
}
void unite(ll x,ll y){
    ll xi=find(x),yi=find(y);
    id[xi]=yi;
}   
int main(){
    cin>>n>>m;
    for(ll i=0;i<n;i++)id[i]=i;
    while(m--){
        cin>>z>>x>>y;
        if(z==1) unite(x,y);
        else if(z==2){
            if(find(x)==find(y))cout<<"Y"<<endl;
            else cout<<"N"<<endl;
        }
    }
    return 0;
}

So will a few lines, not particularly difficult, right?

Guess you like

Origin www.cnblogs.com/tushukai/p/11546291.html