Cod sursa(job #2778972)

Utilizator AACthAirinei Andrei Cristian AACth Data 2 octombrie 2021 14:15:30
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
#define cin f
#define cout g
#define int long long
const int Max = 1e5 + 1;
void nos()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
}
class DSU{
private: 
	vector < int > parent;
	vector < int > rang;
public:
	void init_empty(int n)
	{
		parent.resize(n + 1);
		rang.resize(n + 1);
		for(int i=1;i<=n;i++)
			parent[i] = i,rang[i] = 1;
	}
	int find(int x)
	{
		int nod	,y;
		for(nod = x;parent[nod] != nod;nod = parent[nod]);
		while(parent[x] != x)
		{
			y = parent[x];
			parent[x] = nod;
			x = y;
		}
		return nod;
	}
	void merge(int x, int y)
	{
		x = find(x);
		y = find(y);
		if(x == y)
			return;
		if(rang[x] < rang[y])
			swap(x,y);
		rang[x] += rang[y];
		parent[y] = x;	
	}
	void debug(int n)
	{
		int i;
		for(i=1;i<=n;i++)
			cout<<parent[i]<<' ';
		cout<<'\n';
		for(i=1;i<=n;i++)
			cout<<rang[i]<<' ';
		cout<<'\n';


	}
};
int n,m;
void read()
{
	f>>n>>m;
}
void solve()
{
    DSU dsu;
    dsu.init_empty(n);
    while(m --)
    {
    	int task, x,y;
    	f>>task>>x>>y;
    	if(task == 1)
    		dsu.merge(x,y);
    	else
    	{
    		if(dsu.find(x) == dsu.find(y))
    			cout<<"DA\n";
    		else
    			cout<<"NU\n";
    	}
    	//dsu.debug(n);
    	//cout<<'\n';
    	
    }
    
}
void restart()
{

}
int32_t main()
{
    nos();

        read();
        solve();
        restart();
    
    return 0;
}