Cod sursa(job #1448488)

Utilizator AndreiITCuriman Andrei AndreiIT Data 7 iunie 2015 12:01:32
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
#define MAX 100014
int tata[MAX];
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
int str(int nod);
void unire(int nod1, int nod2);
int main()
{
    int n,m,x,y,z;
    fin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        tata[i]=i;
        //rang[i]=1;
    }
    for(int i=1; i<=m; ++i)
    {
        fin>>z>>x>>y;
        if(z==1)
        {
            x=str(x);
            y=str(y);
            unire(x,y);
        }
        else
        {
            if(str(y)==str(x))
                fout<<"DA"<<'\n';
            else
                fout<<"NU"<<'\n';
        }
    }
    return 0;
}
int str(int nod)
{
    int x=nod;
    while(nod!=tata[nod])
        nod=tata[nod];
    while(x!=tata[x])
    {
        x=tata[x];
        tata[x]=nod;
    }
    return nod;
}
void unire(int nod1, int nod2)
{
    srand (time(NULL));
    int x=rand()%2;
    if(x==0)
        tata[nod2]=nod1;
    else
        tata[nod1]=nod2;
}