Cod sursa(job #3308986)

Utilizator ViAlexVisan Alexandru ViAlex Data 30 august 2025 18:11:00
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.66 kb
#include<iostream>
#include<fstream>
using namespace std;

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

const int MAX_N = 1e5;
int father[MAX_N+1];
int depth[MAX_N+1]; // depth[x] the depth of the subtree rooted at  x

int root(int x) {
	while(father[x] != 0){
		x = father[x];
	}
	return x;
}

void merge(int a, int b) {
	if (depth[a] > depth[b]) {
		father[b] = a;
	} else if (depth[a] < depth[b]) {
		father[a] = b;
	} else{
		father[a] = b;
		depth[b]++;
	}
}


int main(){
	int n, m;
	int a, b, q;
	in>>n>>m;
	while(m--){
		in>>q>>a>>b;
		if (q == 1){
			merge(root(a), root(b));
		} else{
			out<<(root(a) == root(b) ? "DA": "NU")<<'\n';
		}
	}
	return 0;
}