Cod sursa(job #1206615)

Utilizator unsilviuContvechidontdeactivatepls unsilviu Data 10 iulie 2014 17:03:48
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <fstream>
using namespace std;

void join(int x, int y, int dad[],int harb[] ) {
    int xup,yup,sw;

    xup=x;
    yup=y;

    while(dad[xup]!=xup)        //Find X root
        xup=dad[xup];

    while (dad[x]!=x) {       //Join X and ancestors to root
        sw=x;
        x=dad[x];
        dad[sw]=xup;
    }

    while(dad[yup]!=yup)        //Find Y root
        yup=dad[yup];

    while (dad[y]!=y) {       //Join Y and ancestors to root
        sw=y;
        y=dad[y];
        dad[sw]=yup;
    }

    if (harb[x]<harb[y])       //Join smaller tree (sorted by height upper bound) to the larger
        dad[x]=y;
    else
        dad[y]=x;

    if (harb[x]==harb[y])      //If they are equal, after they are joined the height upper bound increases by 1
        harb[y]++;

}

int query(int x, int y, int dad[], int harb[]) {
    int xup,yup,sw;

    xup=x;
    yup=y;

    while(dad[xup]!=xup)        //Find X root
        xup=dad[xup];

    while (dad[x]!=x) {       //Join X and ancestors to root
        sw=x;
        x=dad[x];
        dad[sw]=xup;
    }

    while(dad[yup]!=yup)        //Find Y root
        yup=dad[yup];

    while (dad[y]!=y) {       //Join Y and ancestors to root
        sw=y;
        y=dad[y];
        dad[sw]=yup;
    }

    if (xup==yup)
        return 1;
    else
        return 0;
}

int main() {
    int dad[100001],harb[100001],i,x,y,opt,ans,n,m;  //harb is height of the tree
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");
    in>>n>>m;

    for (i=1; i<=n; i++) {
        dad[i]=i;
        harb[i]=1;
    }

    for (i=1; i<=m; i++) {
        in>>opt>>x>>y;

        if (opt==1)
            join(x,y,dad,harb);
        else if (opt==2) {
            ans=query(x,y,dad,harb);
            if (ans)
                out<<"DA"<<'\n';
            else
                out<<"NU"<<'\n';
        }

    }

    in.close();
    out.close();
    return 0;
}