Cod sursa(job #3309702)

Utilizator mihai.25Calin Mihai mihai.25 Data 7 septembrie 2025 21:23:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>

#include <vector>

using namespace std;

int n, m;

vector<int> T;

int get_root (int node) {

	int aux = node;

	while (T[node] > 0)
		node = T[node];
	
	int root = node;

	node = aux;

	while (node != root) {

		aux = T[node];

		T[node] = root;

		node = aux;
	}

	return root;
}

void join (int x, int y) {

	int root_x = get_root (x), root_y = get_root (y);

	if (T[root_x] <= T[root_y]) {

		T[root_x] += T[root_y];

		T[root_y] = root_x;
	}
	else {

		T[root_y] += T[root_x];

		T[root_x] = root_y;
	}
}

int main () {

	ifstream fin ("disjoint.in");

	ofstream fout ("disjoint.out");

	fin >> n >> m;

	T.assign(n + 1, -1);

	for (int i = 1; i <= m; ++i) {

		int cod, x, y;

		fin >> cod >> x >> y;

		if (cod == 1)
			join (x, y);
		else {

			if (get_root (x) == get_root (y))
				fout << "DA\n";
			else
				fout << "NU\n";
		}
	}

	return 0;
}