Cod sursa(job #2374818)

Utilizator pand4_38Vasilevici Vasia pand4_38 Data 7 martie 2019 20:38:06
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>
#define Nmax 100020
using namespace std;

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

int comp[Nmax],grad[Nmax];
int N,M;

int find(int x)
{
    int R,next;
    for(R=x;comp[R]!=R;R=comp[R]);

    for(;comp[x]!=x;)
    {
        next=comp[x];
        comp[x]=R;
        x=next;
    }
    return R;
}

void unire(int x,int y)
{
    if(grad[y]<grad[x])
        comp[y]=x;
    else comp[x]=y;
    if(grad[x]==grad[y])grad[y]++;

}

int main()
{
    fin>>N>>M;
    for(int i=1;i<=N;++i)
    {
        comp[i]=i;
        grad[i]=1;
    }
    int op,x,y;
    for(int i=1;i<=M;++i)
    {
        fin>>op>>x>>y;
        if(op==2)
        {
            if(find(x)==find(y))fout<<"DA\n";
            else fout<<"NU\n";
        }
        else
        {
            if(find(x)==find(y))return 0;
            unire(find(x),find(y));
        }
    }
    return 0;
}