Cod sursa(job #2253141)

Utilizator AnDrEeA1915Monea Andreea AnDrEeA1915 Data 3 octombrie 2018 17:53:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/c++io.h>
#include <fstream>

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

#define nmax 100020

int n, m, f[nmax], rang[nmax];

int search(int x)
{
    int i, aux;
    for ( i = x; f[i] != i; i = f[i]);
    for (; f[x] != x;)
    {
        aux = f[x];
        f[x] = i;
        x = aux;
    }
    return i;
}

void unite(int x, int y)
{
    if (rang[x] > rang[y])
        f[y] = x;
            else f[x] = y;
    if (rang[x] == rang[y]) rang[y]++;
}

int main()
{
    fin >> n >> m;

    int  x, y, cod;
    for (int i = 1; i <= n; ++i)
    {
        f[i] = i;
        rang[i] = 1;
    }

    for (int i = 1; i <= m; ++i)
    {
        fin >> cod >> x >> y;

        if (cod == 2){
            if (search(x) == search(y)) fout << "DA\n";
                else fout << "NU\n";
        }
            else
                {
                    if (search(x) == search(y)) {
                        fout << i;
                        return 0;
                    }
                    unite(search(x), search(y));
                }
    }

    return 0;
}