Cod sursa(job #2422065)

Utilizator Neamtu_StefanStefan Neamtu Neamtu_Stefan Data 17 mai 2019 09:00:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
#include <fstream>

using namespace std;

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

vector <int> cnt, root;
int n, m;

void init() {
    cnt.push_back(0x3f3f3f3f);
    root.push_back(0x3f3f3f3f);
    for(int i = 1; i <= n; ++i) {
        cnt.push_back(1);
        root.push_back(i);
    }
}

int Root(int x) {
    int y;
    for(y = x; y != root[y]; y = root[y]);
    while (x != root[x]) {
        int temp = root[x];
        root[x] = y;
        x = temp;
    }
    return y;
}

void Union(int x, int y) {
    if (cnt[x] > cnt[y]) {
        root[y] = x;
    } else {
        root[x] = y;
    }
    if (cnt[x] == cnt[y])
        ++cnt[y];
}

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

    init();

    while(m) {
        --m;
        int cod;
        fin >> cod;
        if (cod == 1) {
            int x, y;
            fin >> x >> y;
            Union(Root(x), Root(y));
        } else {
            int x, y;
            fin >> x >> y;
            if (Root(x) == Root(y))
                fout << "DA\n";
            else fout << "NU\n";
        }
    }
    for(int i = 1; i <= n; ++i) {
        cout << Root(i) << " ";
    }
    return 0;
}