Cod sursa(job #3308988)

Utilizator ViAlexVisan Alexandru ViAlex Data 30 august 2025 18:14:38
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.7 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) {
	if (father[x] == 0){
		return x;
	}
	int r = root(father[x]);
	father[x] = r;
	return r;
}

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;
}