Pagini recente » Cod sursa (job #974650) | Cod sursa (job #1367047) | Cod sursa (job #1356663) | Cod sursa (job #1243627) | Cod sursa (job #2083714)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
const int Nmax = 1e5 + 10;
int tata[Nmax], nivel[Nmax];
void cod_1(int x, int y) //unesc multimea in care se afla x cu multimea in care se afla y
{
if(nivel[x] < nivel[y]) // arborele cu nivelul mai mic in unesc de cel cu nivelul mai mare
tata[x] = y;
else
tata[y] = x;
if(nivel[x] == nivel[y]) { // daca nivelul este acelasi pentru cei doi arbori atunci cresc oricare din cele doue nivele
tata[y] = x;
nivel[x]++;
}
}
int cod_2(int x)
{
int root = x;
while(tata[root] != root) root = tata[root]; // am determinat radacina nodului x
while(tata[x] != root) { // am creat o legatura de la fiecare nod prin care trece x la radacina acestuia
int aux = tata[x];
tata[x] = root;
x = aux;
}
return root;
}
int main()
{
int n, m;
fin >> n >> m;
for(int i = 1; i <= m; ++i) {
tata[i] = i;
nivel[i] = 1;
}
for(int i = 1; i <= m; i++) {
int cod, x, y;
fin >>cod >> x >> y;
if(cod == 1) {
cod_1(cod_2(x), cod_2(y));
}
if(cod == 2) {
if(cod_2(x) == cod_2(y))
fout << "DA" << '\n';
else
fout << "NU" << '\n';
}
}
return 0;
}