Cod sursa(job #1637705)

Utilizator Alex1234Alexandru Posea Alex1234 Data 7 martie 2016 18:49:48
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <cstdio>
#define MAXI 100020

using namespace std;
int Arb[MAXI],rang[MAXI];
int N,M;
FILE *f1,*f2;

int cauta(int x)
{
    int a,b;
    for(a=x; Arb[a]!=a ; a=Arb[a]);
    for(; Arb[x]!=x;)
    {
        b=Arb[x];
        Arb[x]=a;
        x=b;
    }
    return a;
}

void uneste(int x,int y)
{
    if(rang[x]>rang[y])
        Arb[y]=x;
    else
        Arb[x]=y;
    if(rang[x]==rang[y])
        rang[y]++;
}

int main()
{
    f1=fopen("disjoint.in","r");
    f2=fopen("disjoint.out","w");
    fscanf(f1,"%d%d",&N,&M);
    for(int i=1; i<=N; i++)
        Arb[i]=i,rang[i]=i;
    int a,b,c;
    while(fscanf(f1,"%d%d%d",&a,&b,&c)+1)
    {
        if(a==2)
        {
            if(cauta(b)==cauta(c))
                fprintf(f2,"DA\n");
            else
                fprintf(f2,"NU\n");
        }
        else
        {
            if(cauta(b)==cauta(c))
                return 0;
            uneste(b,c);
        }
    }
    return 0;
}