Cod sursa(job #1814479)

Utilizator kikiandreiCristian Andrei Popescu kikiandrei Data 24 noiembrie 2016 07:58:50
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int N,M,cod,x,y;
int peste[100001],h[100001];

int find(int x)
{
    if (peste[x]==x) return x;
    else
    {
        peste[x]=find(peste[x]);
        return peste[x];
    }
}

int reuniune(int x, int y)
{
    int i,j;
    i=find(x);
    j=find(y);
    if (h[i]>h[j])
    {
        peste[j]=i;
    }
    else if (h[i]<h[j])
    {
        peste[i]=j;
    }
    else
    {
        peste[j]=i;
        h[i]++;
    }
}

int main()
{
    in>>N>>M;
    for (int i=1; i<=N; i++)
    {
        peste[i]=i;
        h[i]=1;
    }
    for (int i=1;i<=M;i++)
    {
        in>>cod>>x>>y;
        if (cod==1) reuniune(x,y);
        else
        {
            if (find(x)==find(y)) out<<"DA\n";
            else out<<"NU\n";
        }
    }

    return 0;
}