Pagini recente » Cod sursa (job #2421096) | Cod sursa (job #2901704) | Cod sursa (job #557409) | Cod sursa (job #2326402) | Cod sursa (job #1254894)
/// Craciun Catalin
/// Disjoint
/// Paduri de multimi distincte
#include <iostream>
#include <fstream>
#include <cassert>
#define NMax 100005
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int n,m;
int F[NMax]; /// F[i] = tatal lui i
int R[NMax]; /// R[i] = inaltimea arborelui format cu nodul i
int findE(int x) {
int e,aux;
for (e = x; F[e] != e; e = F[e]);
for (;F[x] != x;) {
aux = F[x];
F[x] = e;
x = aux;
}
return e;
}
void update(int x, int y) {
int firstRoot = findE(x);
int secondRoot = findE(y);
if (R[firstRoot] < R[secondRoot]) {
F[firstRoot] = secondRoot;
} else if (R[firstRoot] > R[secondRoot]) {
F[secondRoot] = firstRoot;
} else {
F[secondRoot] = firstRoot;
R[firstRoot]++;
}
}
int main() {
f>>n>>m;
for (int i=1;i<=n;i++) F[i] = i, R[i] = 1;
for (int i=1;i<=m;i++) {
int type;
f>>type;
assert(type == 1 || type == 2);
if (type == 1) {
int x,y;
f>>x>>y;
update(x,y);
} else {
int x,y;
f>>x>>y;
if (findE(x) == findE(y))
g<<"DA\n";
else
g<<"NU\n";
}
}
f.close(); g.close();
return 0;
}