Cod sursa(job #2939097)

Utilizator mirceaspPetcu Mircea mirceasp Data 12 noiembrie 2022 23:46:47
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <bits/stdc++.h>

using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
#define maxn 100001
int tata[maxn],rang[maxn];
int n, m;
int root(int x)
{
    while (tata[x] != x)
    {
        x = tata[x];
        tata[x] = tata[tata[x]];

    }
    return x;
}
int main() {
    int op, x, y;
    f>>n>>m;
    for (int i = 1; i <= n; i++) {
        tata[i] = i;
        rang[i] = 1;
    }
    for (int i = 0; i < m; i++) {
        f >> op >> x >> y;
        if (op == 1) {
            if(root(x) != root(y)) {
                if (rang[x] <= rang[y]) {
                    tata[x] = tata[y];
                    for(int j = 0;j<n;j++)
                        if(tata[j] == x)
                            tata[j] = tata[y];
                    rang[y] += rang[x];
                } else {
                    tata[y] = x;
                    for(int j = 0;j<n;j++)
                        if(tata[j] == y)
                            tata[j] = tata[x];
                    rang[x] += rang[y];
                }
            }
        }
        else if(op == 2)
        {
            if(tata[x] == tata[y])
                g<<"DA"<<'\n';
            else
                g<<"NU"<<'\n';
        }
    }
    f.close();
    g.close();
    return 0;
}