Pagini recente » Cod sursa (job #641846) | Cod sursa (job #3201975) | Cod sursa (job #1837932) | Cod sursa (job #2055709) | Cod sursa (job #2134188)
#include <iostream>
#include <vector>
#include <fstream>
#include <stack>
#define NMAX (100000 + 3)
#define MMAX (1000000 + 3)
using namespace std;
void Unite(int a, int b, int father[], int rank[]) {
while (father[a] > 0) {
a = father[a];
}
while (father[b] > 0) {
b = father[b];
}
if (rank[a] > rank[b]) {
father[b] = a;
rank[a] += rank[b];
} else {
father[a] = b;
rank[b] += rank[a];
}
}
bool Check(int a, int b, int father[]) {
while (father[a] > 0) {
a = father[a];
}
while (father[b] > 0) {
b = father[b];
}
int set_a = father[a], set_b = father[b];
while (father[a] > 0) {
int tmp = father[a];
father[a] = set_a;
a = tmp;
}
while (father[b] > 0) {
int tmp = father[b];
father[b] = set_b;
b = tmp;
}
return set_a == set_b;
}
int main() {
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int n, q;
f >> n >> q;
int father[NMAX];
int rank[NMAX];
for (int i = 1; i <= n; ++i) {
father[i] = -i;
rank[i] = 1;
}
for (; q; --q) {
int type, a, b;
f >> type >> a >> b;
if (type == 1) {
Unite(a, b, father, rank);
} else {
if (Check(a, b, father)) {
g << "DA\n";
} else {
g << "NU\n";
}
}
}
return 0;
}