Cod sursa(job #2934532)

Utilizator ViAlexVisan Alexandru ViAlex Data 6 noiembrie 2022 09:59:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
#include<iostream>
#include<fstream>
#include<deque>
#include<algorithm>
#include<vector>
using namespace std;

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

vector<int> father,depth;

// Merge the two sets.
// A and B must be roots.
void merge(int a,int b){
	if(depth[a]==depth[b]){
		father[a]=b;
		depth[b]++;
	}
	else if(depth[a]<depth[b]){
		father[a]=b;
	}
	else{
		father[b]=a;
	}
}

// Get the set of the node.
int root(int node){
	while(father[node]!=0){
		node=father[node];
	}
	return node;
}

void solve(){
	int n,m,c,x,y;

	in>>n>>m;

	father.resize(n+1,0);
	depth.resize(n+1,0);

	for(int i=0;i<m;i++){
		in>>c>>x>>y;
		if(c==1){
			merge(root(x),root(y));
		}
		else{
			out<<(root(x)==root(y)?"DA":"NU")<<'\n';
		}
	}
}


int main(){
	solve();

	return 0;
}