Pagini recente » Monitorul de evaluare | Cod sursa (job #290006) | Cod sursa (job #2005889) | Cod sursa (job #1205946) | Cod sursa (job #1806189)
#include <fstream>
#include <vector>
using namespace std;
ifstream f{ "disjoint.in" };
ofstream q{ "disjoint.out" };
int find(const int& x, vector<int>& tata)
{
int aux = x;
while (aux != tata[aux])
{
aux = tata[aux];
}
//path compression;
int pAux = x;
int interm;
while (pAux != tata[pAux])
{
interm = tata[pAux];
tata[pAux] = aux;
pAux = interm;
}
return aux;
}
void unionSet(int x, int y, vector<int>& tata, vector<int>& rang)
{
int px, py;
px = find(x, tata);
py = find(y, tata);
if (px == py) return;
if (rang[px] >= rang[py])
{
tata[py] = px;
if (rang[px] == rang[py]) rang[px]++;
}
else
{
tata[px] = py;
}
}
int main()
{
int n, m, op, y, x, px, py;
f >> n >> m;
vector<int> tata(n + 1, 0);
vector<int> rang(n + 1, 0);
for (int i = 0; i <= n; ++i) tata[i] = i, rang[i] = 0;
while (m--)
{
f >> op >> x >> y;
if (op == 1) unionSet(x, y, tata, rang);
else {
px = find(x, tata);
py = find(y, tata);
(px == py) ? q << "DA\n" : q << "NU\n";
}
}
f.close();
q.close();
return 0;
}