Cod sursa(job #3229705)

Utilizator PitigoiOlteanEmanuelPitigoi Oltean Emanuel PitigoiOlteanEmanuel Data 17 mai 2024 09:43:32
Problema Paduri de multimi disjuncte Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <map>
#include <algorithm>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

	int N;
	int sol[100001];
	map<int,int> parent;
	map<int,int> sizes;
	void init(int n)
	{
		N=n;
		for(int i=1;i<=N;i++)
		{
			parent[i]=i;
			sizes[i]=1;
		}
	}
	int find(int u)
	{
		if(u==parent[u])
        {
            return u;

        }

		return parent[u]=find(parent[u]);
	}
	void unite(int u,int v)
	{
		u=find(u);
		v=find(v);
		if(u==v)
		return;
		if(sizes[v]>sizes[u])
		swap(u,v);
		parent[v]=u;
		sizes[u]+=sizes[v];

}

int main()
{
	int n,m,x,y;
	cin>>n>>m;
	init(n);
	int media8;
	for(int i=1;i<=m;i++)
	{
		cin>>media8>>x>>y;
		if(media8==1)
        {
            unite(x,y);
        }
        else
        {
            if(find(x)==find(y))
            {
                cout<<"DA"<<'\n';
            }
            else
            {
                cout<<"NU"<<'\n';

            }
        }
	}


}