Pagini recente » Cod sursa (job #1013356) | Cod sursa (job #880585) | Cod sursa (job #1709159) | Cod sursa (job #1231477) | Cod sursa (job #2751983)
#include <bits/stdc++.h>
using namespace std;
/// varianta cu compresie -> O(NlogN)
const int MAX_N = 1e5;
int n;
int sef[1 + MAX_N];
int gaseste_sef_rec (int x) {
if (sef[x] == x)
return x;
sef[x] = gaseste_sef_rec (sef[x]);
return sef[x];
}
int gaseste_sef_nerec (int x) {
int copie_x = x;
while (sef[x] != x)
x = sef[x];
int sefx = x;
x = copie_x;
while (sef[x] != x) {
int y = sef[x];
sef[x] = sefx;
x = y;
}
return sefx;
}
void uneste (int x, int y) { /// functie care uneste x si y
int tx = gaseste_sef_rec (x);
int ty = gaseste_sef_rec (y);
if (tx != ty) { /// daca x si y nu sunt deja in aceeasi multime
sef[ty] = tx;
}
}
void initializare () {
for (int i = 1; i <= n; i++)
sef[i] = i; /// fiecarui element ii dam cate o multime in care el este sef suprem
}
void query (int x, int y) { /// daca x si y sunt in aceeasi multime
int tx = gaseste_sef_rec (x);
int ty = gaseste_sef_rec (y);
if (tx == ty) {
cout << "DA\n";
}
else {
cout << "NU\n";
}
}
int main () {
freopen ("disjoint.in", "r", stdin);
freopen ("disjoint.out", "w", stdout);
ios::sync_with_stdio (false);
cin.tie (0); cout.tie (0);
int m;
cin >> n >> m;
initializare ();
for (int i = 1; i <= m; i++) {
int tip, x, y;
cin >> tip >> x >> y;
if (tip == 1) { /// operatia de unire
uneste (x, y);
}
else { /// query
query (x, y);
}
}
return 0;
}