Cod sursa(job #3169084)

Utilizator CastielGurita Adrian Castiel Data 14 noiembrie 2023 10:28:48
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
/******************************************************************************

                              Online C++ Compiler.
               Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int n,m,a,b,c,T[100005];
int get_root(int node) {
	int aux = node;
	while (T[node] > 0)
		node = T[node];
	int root = node;
	// mai parcurg odata acelasi drum si unesc nodurile de root
	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);  // radacina arborelui lui x
	int root_y = get_root(y);  // radacina arborelui lui y
	if (root_x == root_y)  // sunt deja in acelasi arbore
		return;
	if (T[root_x] <= T[root_y]) {  // arborele lui x are mai multe noduri
		T[root_x] += T[root_y];
		T[root_y] = root_x;  // legam arborele lui y de arborele lui x
	} else {
		T[root_y] += T[root_x];
		T[root_x] = root_y;  // legam arborele lui x de arborele lui y
	}
}
bool query(int x, int y) {
	// x si y sunt in acelasi arbore daca au aceeasi radacina
	return get_root(x) == get_root(y);
}
int main()
{
    fin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        fin>>a>>b>>c;
        if(a==1)
        {
            join(b,c);
        }
        else
        {
            if(query(b,c)){fout<<"DA"<<endl;}
            else{fout<<"NU"<<endl;}
        }
    }
    fin.close();
    fout.close();
    return 0;
}