Pagini recente » Cod sursa (job #2991136) | Cod sursa (job #1338441) | Cod sursa (job #440429) | Cod sursa (job #2791354) | Cod sursa (job #1463001)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <assert.h>
const char IN[] = "disjoint.in", OUT[] = "disjoint.out";
const int NMAX = 100000 + 1;
using namespace std;
int N;
int T;
int A[NMAX];
int PI[NMAX];
int RANK[NMAX];
int find(int x)
{
if (PI[x] == x)
return x;
else {
int parent = find(PI[x]);
PI[x] = parent;
return parent;
}
}
void unite(int x, int y)
{
int xRoot = find(x);
int yRoot = find(y);
if (xRoot == yRoot)
return;
//nu sunt in acelasi set disjunct, se adauga arborele
//de rank mai mic la cel de rank mai mare
if (RANK[xRoot] < RANK[yRoot]) {
PI[xRoot] = yRoot;
}
else if (RANK[xRoot] > RANK[yRoot]) {
PI[yRoot] = xRoot;
}
else {
//sunt egale, creste rank-ul
PI[yRoot] = xRoot;
++RANK[xRoot];
}
}
inline void read_data()
{
assert(freopen(IN, "r", stdin));
assert(freopen(OUT, "w", stdout));
assert(scanf("%d %d", &N, &T));
for (int i = 1; i <= N; ++i) {
A[i] = i;
PI[i] = i;
}
while (T--) {
int op, x, y;
assert(scanf("%d %d %d", &op, &x, &y));
switch (op) {
case 1:
unite(x, y);
break;
case 2:
if (find(x) == find(y)) printf("DA\n");
else printf("NU\n");
break;
}
}
fclose(stdin);
fclose(stdout);
}
int main()
{
read_data();
return 0;
}