Cod sursa(job #1705909)

Utilizator razvan3895Razvan-Mihai Chitu razvan3895 Data 21 mai 2016 06:21:56
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <iostream>
#include <vector>


using namespace std;

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


int n;
int tree[100001];
int rang[100001];



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

    if (rang[x] == rang[y]) {
        rang[x]++;
    }
}

int find(int x) {
    int root, node;

    for (root = x; tree[root] != root; root = tree[root]);

    while (x != root) {
        node = tree[x];
        tree[x] = root;
        x = node;
    }

    return root;
}


int main() {
    int m;

    in >> n >> m;

    for (int i = 1; i <= n; ++i) {
        tree[i] = i;
        rang[i] = 0;
    }

    for (int i = 0; i < m; ++i) {
        int c, x, y;

        in >> c >> x >> y;

        if (c == 1) {
            unite(x, y);
        } else {
            if (find(x) == find(y)) {
                out << "DA\n";
            } else {
                out << "NU\n";
            }
        }
    }

    return 0;
}