Cod sursa(job #2241431)

Utilizator PescaruVictorPescaru Victor PescaruVictor Data 15 septembrie 2018 20:07:03
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include <fstream>

using namespace std;

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

int n, m;
int h[100010], tata[100010];

int find(int x)
{
    int cx, aux, next;
    cx = aux = x;
    while(tata[cx])
        cx = tata[cx];
    while(tata[aux])
    {
        next = tata[aux];
        tata[aux] = cx;
        aux = next;
    }
    return cx;
}

void unite(int x, int y)
{
    int px = find(x), py = find(y);
    if(h[px] > h[py])
        tata[py] = px;
    else
        tata[px] = py;
    if(h[px] == h[py])
        ++h[py];
}


int main()
{
    int c, x, y;
    fin>>n>>m;
    for(int i=1; i<=m; ++i)
    {
        fin>>c>>x>>y;
        if(c == 1)
            unite(x, y);
        else
        {
            if(find(x) == find(y))
                fout<<"DA\n";
            else
                fout<<"NU\n";
        }
    }
    return 0;
}