Cod sursa(job #2930586)

Utilizator ViAlexVisan Alexandru ViAlex Data 28 octombrie 2022 20:01:51
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include<iostream>
#include<deque>
#include<algorithm>
#include<vector>
#include<fstream>
using namespace std;

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

vector<int> father,depth;

const int mx=100001;
int n,m,path[mx];

int root(int node){
	int cur=0;

	while(father[node]){
		path[cur++]=node;
		node=father[node];
	}

	for(int i=0;i<cur;i++){
		father[path[i]]=node;
	}

	return node;
}

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

void solve(){
	in>>n>>m;
	father.resize(n+1);
	depth.resize(n+1);
	int a,b,c;

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

int main(){
	solve();

	return 0;
}