Cod sursa(job #2335470)

Utilizator david.sachelarieDavid Sachelarie david.sachelarie Data 4 februarie 2019 09:53:58
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>

using namespace std;

int v[100001];
int father[100001];

int main()
{
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");

    int n,m;
    fin>>n>>m;


    int p,a,b,c,d,cop;
    int i;
    for(i=0;i<m;i++){
        fin>>p>>a>>b;
        if(p==1){
            if(father[a]==0 && father[b]==0){
                father[b]=a;
            }
            else{
                while(father[a]!=0)
                    a=father[a];

                while(father[b]!=0)
                    b=father[b];

                father[b]=a;
            }
        }
        else{
            c=a;
            d=b;
            while(father[a]!=0)
                a=father[a];

            while(father[b]!=0)
                b=father[b];

            if(a==b) fout<<"DA"<<endl;
            else fout<<"NU"<<endl;

            while(c!=a){
                cop=c;
                c=father[c];
                father[cop]=a;
            }

            while(d!=b){
                cop=d;
                d=father[d];
                father[cop]=b;
            }
        }
    }
    fin.close();
    fout.close();
    return 0;
}