Cod sursa(job #1641418)

Utilizator justsomedudePalade Thomas-Emanuel justsomedude Data 8 martie 2016 22:59:57
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include<iostream>
#include<fstream>
#include<vector>
#define MOD 123457

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

int t[100009], c[100009], N;

int Find(int x)
{
    int y, z;
    y = x;
    while (t[x] != 0)
       x = t[x];

    while (t[y] != 0)
    {
        z = t[y];
        t[y] = x;
        y = z;
    }
    return x;
}

void Union (int x, int y)
{
    if (c[x] > c[y])
    {
        c[x] += c[y];
        c[y] = 0;
        t[y] = x;
    }
    else
    {
        c[y] += c[x];
        c[x] = 0;
        t[x] = y;
    }
}

int main ()
{
    int T, tip, x, y;
    fin >> N >> T;
    for (int i=1; i<=T; i++)
    {
       fin >> tip >> x >> y;
       if (tip == 1)
          Union(Find(x), Find(y));
       else
        {
          if (Find(x) == Find(y))
            fout << "DA\n";
          else
            fout << "NU\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}