Cod sursa(job #2376649)

Utilizator AlexTudorAlex Brinza AlexTudor Data 8 martie 2019 16:56:53
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>
using namespace std;

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

const int NMAX=100005;

int m[NMAX],sz[NMAX];

int N,M;

int Find( int x )
{
    int root=x;
    int aux;

    while(m[root]!=root) root=m[root];

    while(m[x]!=root)
    {
        aux=m[x];
        m[x]=root;
        x=m[x];
    }

    return root;
}

void Union(int A , int B)
{
    int root_A=Find(A);
    int root_B=Find(B);

    if(sz[root_A] > sz[root_B])
    {
        sz[root_A]+=sz[root_B];
        m[root_B]=root_A;
    }
    else
    {
        sz[root_B]+=sz[root_A];
        m[root_A]=root_B;
    }
}

void read()
{
    fin>>N>>M;

    for(int i=1;i<=N;++i) { m[i]=i; sz[i]=1;}

    int task,x,y;

    for(int i=1;i<=M;++i)
    {
        fin>>task>>x>>y;

        if(task==1) Union(x,y);
        else
            if(Find(x)==Find(y)) fout<<"DA"<<"\n";
            else fout<<"NU"<<"\n";
    }
}

int main()
{
    read();
    return 0;
}