Cod sursa(job #2485192)

Utilizator sichetpaulSichet Paul sichetpaul Data 1 noiembrie 2019 09:47:34
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>
#define Nmax 100005
using namespace std;

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

int N, M;
int root[Nmax], father[Nmax], h[Nmax];
void change_root(int node, int newRoot) {
   int curr = node;
   while (curr != 0) {
       int nxt = father[curr];
       root[curr] = father[curr] = root[node];
       curr = nxt;
   }
}
void unit(int x, int y) {
    if (h[x] >= h[y]) change_root(y, root[x]);
    else change_root(x, root[y]);
    if (h[x] == h[y]) ++h[x];
}
int main()
{
    f >> N >> M;
    for (int i = 1; i <= N; ++i)
        root[i] = i, h[i] = 1;
    for (int i = 1; i <= M; ++i) {
        int tip, x, y;
        f >> tip >> x >> y;
        if (tip == 2) {
            if (root[x] == root[y]) g << "DA\n";
            else g << "NU\n";
        }
        else unit(x, y);
    }
      for(int i = 1; i <= N; ++i)
          g << h[i] << " ";

    return 0;
}