Pagini recente » Cod sursa (job #1802042) | Cod sursa (job #194527) | Cod sursa (job #1227708) | Cod sursa (job #985829) | Cod sursa (job #2274588)
#include <iostream>
#include <fstream>
#include <vector>
#define NMAX 100001
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
class APM {
private:
int root[NMAX];
int last[NMAX]; /// ultimul element din grup
int next[NMAX]; /// urmatorul element din grup
int groupSize[NMAX]; /// nr de elemente din grup
void resetRoot(int x, int y, int l) {
root[x] = y;
if (x != l) {
resetRoot(next[x], y, l);
}
}
void combine(int x, int y) {
int l = last[y];
next[l] = x;
last[y] = last[x];
resetRoot(x, y, last[x]);
}
public:
APM(int n) {
for (int i = 1; i <= n; ++i ) {
groupSize[i] = 1;
root[i] = i;
next[i] = 0;
last[i] = i;
}
}
int getRoot(int x) { return root[x]; }
void groupRoots(int x, int y) {
int t1 = getRoot(x);
int t2 = getRoot(y);
/// se garanteaza ca t1 != t2
if (groupSize[t1] < groupSize[t2]) {
combine(t1, t2);
} else {
combine(t2, t1);
}
}
};
int main() {
int n, m;
f >> n >> m;
APM a(n);
for (int i = 0; i < m; ++i) {
int type, x, y;
f >> type >> x >> y;
if (type == 1) {
a.groupRoots(x, y);
} else {
int t1 = a.getRoot(x);
int t2 = a.getRoot(y);
if (t1 != t2) {
g << "NU\n";
} else {
g << "DA\n";
}
}
}
return 0;
}