Pagini recente » Cod sursa (job #1199369) | Cod sursa (job #2087476) | Cod sursa (job #744128) | Cod sursa (job #1891623) | Cod sursa (job #1401742)
#include <fstream>
#define NMAX 100001
using namespace std;
int T[NMAX], H[NMAX];
int rep(int nod) {
while (T[nod])
nod = T[nod];
return nod;
}
void compresie(int nod, int r) {
int tata;
while (T[nod]) {
tata = T[nod];
T[nod] = r;
nod = tata;
}
}
bool interogare(int x, int y) {
if (rep(x) == rep(y))
return 1;
return 0;
}
void reuniune(int x, int y) {
int a, b;
a = rep(x);
b = rep(y);
if (H[a] == H[b]) {
T[x] = y;
H[rep(y)]++;
compresie(x, b);
compresie(y, b);
}
else if (H[x] < H[y]) {
T[x] = y;
compresie(x, b);
compresie(y, b);
}
else {
T[y] = x;
compresie(y, a);
compresie(x, a);
}
}
int main() {
int i, n, m;
ifstream in("disjoint.in");
in >> n >> m;
int t, x, y, ok;
ofstream out("disjoint.out");
for (i = 1; i <= m; i++) {
in >> t >> x >> y;
if (t == 1)
reuniune (x, y);
else {
ok = interogare (x, y);
if (!ok)
out << "NU\n";
else out << "DA\n";
}
}
out.close();
in.close();
return 0;
}