Cod sursa(job #2632317)

Utilizator popoviciAna16Popovici Ana popoviciAna16 Data 2 iulie 2020 19:15:04
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <fstream>
using namespace std;
 
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int t[100001], h[100001];

int find(int x) //returneaza reprezentantul lui x
{
    int r, y, y2;
    r = x;
    while (t[r] != 0)
        r = t[r];
    y = x;
    while (y != r)
    {
        y2 = t[y];
        t[y] = r;
        y = y2;
    }
    return r;
}

void unire(int x, int y)
{
    if (h[x] < h[y])
        t[x] = y;
    else if (h[x] > h[y])
        t[y] = x;
    else
    {
        t[x] = y;
        h[y]++;
    }
}

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