Cod sursa(job #1241200)

Utilizator Andreid91Ciocan Andrei Andreid91 Data 12 octombrie 2014 22:46:22
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <iostream>
#include <fstream>
#include <string>

#define size 200000

using namespace std;

int n, root[size], G[size];

void join(int x, int y) {
    int tx, ty, father;
    for (tx = x; root[tx] != tx; tx = root[tx]);
    for (ty = y; root[ty] != ty; ty = root[ty]);

    if (G[tx] > G[ty]) {
        root[ty] = tx;
        father = tx;
    } else if (G[tx] < G[ty]) {
        root[tx] = ty;
        father = ty;
    } else {
        root[ty] = tx;
        G[tx] ++;
        father = tx;
    }

    for (int it = x, aux; it != root[it]; aux = it, it = root[it], root[aux] = father );
    for (int it = y, aux; it != root[it]; aux = it, it = root[it], root[aux] = father );
}

string query( int x, int y) {
    int tx = x, ty = y;
    for (; tx != root[tx]; tx = root[tx]);
    for (; ty != root[ty]; ty = root[ty]);

    for (int it = x, aux; it != root[it]; aux = it, it = root[it], root[aux] = tx);
    for (int it = y, aux; it != root[it]; aux = it, it = root[it], root[aux] = ty);

    if (tx == ty) {
        return "DA";
    } else {
        return "NU";
    }
}

void solve() {
    ofstream g("disjoint.out");
    ifstream f("disjoint.in");
    int m;
    f >>n >> m;
    for (int i = 1 ;i <= n ;i++){
        root[i] = i;
        G[i] = 1;
    }
    for (;m;--m) {
        int op, x, y;
        f >> op >> x >> y;
        if ( op == 1) {
            join(x, y);
        } else {
            g << query(x, y)<<'\n';
        }
    }
    g.close();
    f.close();
}

int main()
{
    solve();
    return 0;
}