Cod sursa(job #3136760)

Utilizator AlexandruIoan20Moraru Ioan Alexandru AlexandruIoan20 Data 8 iunie 2023 13:34:53
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
#include <fstream>
#include <algorithm>
using namespace std; 

ifstream cin("disjoint.in"); 
ofstream cout("disjoint.out"); 

int N, M; 
int t[100006]; 

void Union(int a, int b) {
	t[a] = b; 
}

int Find(int x) {
	int rad = x, y;

	while (t[rad] != 0) {
		rad = t[rad]; 
	} 

	while (x != rad) {
		y = t[x]; 
		t[x] = rad;
		x = y; 
	}

	return rad; 
}

bool kruskal(int x, int y) {
	int radx = Find(x); 
	int rady = Find(y); 

	return radx == rady; 
}

int main() {
	cin >> N >> M; 

	int x, y, cod; 
	for (int i = 1; i <= M; i++)
	{
		cin >> cod >> x >> y; 
		if (cod == 1) {
			Union(x, y); 
		}
		else {
			if (kruskal(x, y)) {
				cout << "DA" << '\n'; 
			}
			else {
				cout << "NU" << '\n'; 
			}
		}
	}
	return 0; 
}