Cod sursa(job #1888406)

Utilizator ifrimencoAlexandru Ifrimenco ifrimenco Data 22 februarie 2017 09:05:46
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
#include <fstream>
#define nmax 100001
using namespace std;
int tata[nmax];
int h[nmax];

void unire (int x, int y)
{

    if (h[x]>h[y]) tata[y]=x;
    else {tata[x]=y;
    if (h[x]==h[y]) h[y]++;}
}

int gasire (int x)
{
    int r=x;
    while (tata[r]) r=tata[r];
    int y=x, t;
    while (y!=r)
    {
        t=tata[y];
        tata[y]=r;
        y=t;
    }
    return r;
}

int main()
{
    int n, m, i, q, a, b;
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    f >> n >> m;
    for (i=1; i<=n; ++i)
        tata[i]=0;
    for (i=1; i<=m; ++i)
    {
        f >> q >> a >> b;
    if (q==1)
    { if (gasire(a)!=gasire(b)) unire(a,b);}
    else {
    if (gasire(a)==gasire(b)) g <<"DA\n";
    else g << "NU\n";}

    }

    return 0;
}