Cod sursa(job #2850888)

Utilizator carinamariaCarina Maria Viespescu carinamaria Data 17 februarie 2022 18:05:14
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
int n, T[100001], i, x, y, m, nr;
int get_root(int node){
	int aux=node;
	while (T[node]>0)
		node=T[node];
	int root=node;
	node=aux;
	while (node!=root){
		aux=T[node];
		T[node]=root;
		node=aux;
	}
	return root;
}
void join(int x, int y){
	int root_x=get_root(x);
	int root_y=get_root(y);
	if (root_x==root_y)
		return;
	if (T[root_x]<=T[root_y]){
		T[root_x]+=T[root_y];
		T[root_y]=root_x;
	}else{
		T[root_y]+=T[root_x];
		T[root_x]=root_y;
	}
}
bool query(int x, int y){
	return get_root(x)==get_root(y);
}
int main() {
    cin>>n>>m;
    for(i=1;i<=m;i++){
        cin>>x;
        if(x==1){
            cin>>x>>y;
            join(x, y);
        }
        else{
            cin>>x>>y;
            nr=query(x, y);
            if(nr==1)
                cout<<"DA"<<"\n";
            else
                cout<<"NU"<<"\n";
        }

    }






}