Cod sursa(job #3236926)

Utilizator SilviuC25Silviu Chisalita SilviuC25 Data 3 iulie 2024 16:44:56
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>
#define int long long
using namespace std;

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

const int MAX_NUM = 1e5;

int n, m, parent[MAX_NUM], treeRank[MAX_NUM];

int find(int x) {
	int root = x;
	while (parent[root] != root) {
		root = parent[root];
	}
	while (x != root) {
        x = parent[x];
        parent[x] = root;
	}
	return root;
}

void unify(int x, int y) {
	if (treeRank[x] > treeRank[y]) {
		parent[y] = x;
	} else {
        parent[x] = y;
	}
	if (treeRank[x] == treeRank[y]) {
        ++treeRank[y];
	}
}

signed main() {
    fin >> n >> m;
	for (int i = 1; i <= n; ++i) {
		parent[i] = i;
		treeRank[i] = 1;
	}
	for (int i = 0; i < m; ++i) {
        int x, y, cod;
        fin >> cod >> x >> y;
		if (cod == 2){
			if (find(x) == find(y)) {
                fout << "DA\n";
			} else {
                fout << "NU\n";
			}
		} else {
            unify(find(x), find(y));
        }
	}
	return 0;
}