Cod sursa(job #3152142)

Utilizator iuliageambazuGeambazu Iulia iuliageambazu Data 24 septembrie 2023 08:42:12
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>

using namespace std;

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

vector <int> par;
vector <int> sz;

void initialize (int n)
{
	par.resize(n+1);
	sz.resize(n+1 , 1);
	for (int i = 1; i <= n; i++)
	{
		par[i] = i;
	}
}

int Find (int nod)
{
	if (par[nod] == nod) return nod;
	else return par[nod] = Find(par[nod]);
}

void unite (int x , int y)
{
	int repX = Find(x) , repY = Find(y);
    //if (s[repX] < s[repY]) swap(repX , repY);
	if (repX != repY)
    {
	if(sz[repX] > sz[repY])
		par[repY]=repX, sz[repX]+=sz[repY];
    else
        par[repX]=repY, sz[repY]+=sz[repX];
    }
}

int main()
{
    int n, m;
    fin>>n>>m;
    initialize(n);
    int cod, a, b;
    for(int i=1; i<=m; i++)
    {
        fin>>cod>>a>>b;
        if(cod==1)
            unite(a, b);
        else
            {
                if(Find(a)==Find(b))
                    fout<<"DA"<<'\n';
                else
                    fout<<"NU"<<'\n';
            }
    }
    return 0;
}