Pagini recente » Cod sursa (job #2146097) | Cod sursa (job #2928202) | Cod sursa (job #599523) | Cod sursa (job #2744686) | Cod sursa (job #2751973)
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5;
int n;
int sef[1 + MAX_N];
int gaseste_sef_rec (int x) {
if (sef[x] == x)
return x;
return gaseste_sef_rec (sef[x]);
}
int gaseste_sef_nerec (int x) {
while (sef[x] != x)
x = sef[x];
return x;
}
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);
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;
}