Cod sursa(job #2678707)

Utilizator davidcotigacotiga david davidcotiga Data 28 noiembrie 2020 15:17:26
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>

#define MAX 100020

using namespace std;

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

int TT[MAX], RG[MAX];
int N, M;

int find(int x) {
	int R, y;

	for (R = x; TT[R] != R; R = TT[R]);

	while (TT[x] != x) {
		y = TT[x];
		TT[x] = R;
		x = y;
	}

	return R;
}

void unite(int x, int y) {

	if (RG[x] > RG[y])
		TT[y] = x;
	else
		TT[x] = y;

	if (RG[x] == RG[y])
		RG[y]++;
}

int main() {

	fin >> N >> M;

	for (int i = 1; i <= N; ++i) {
		TT[i] = i;
		RG[i] = 1;
	}

	int x, y, cd;
	for (int i = 1; i <= M; ++i) {
		fin >> cd >> x >> y;

		if (cd == 2) {
			if (find(x) == find(y))
				fout << "DA\n";
			else
				fout << "NU\n";
		}
		else {
			unite(find(x), find(y));
		}
	}

	return 0;
}