Pagini recente » Cod sursa (job #1730399) | Cod sursa (job #1581193) | Cod sursa (job #2356118) | Cod sursa (job #66696) | Cod sursa (job #2896954)
#include <bits/stdc++.h>
#define INF ((int)1e9)
#define NMAX ((int)1e5)
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int n, m;
int conex_comp[NMAX + 1];
int conex_rank[NMAX + 1];
int get_root(int node) {
if (conex_comp[node] == node) {
return node;
}
int new_root = get_root(conex_comp[node]);
conex_comp[node] = new_root;
return new_root;
}
int unite(int a, int b) {
int root_a = get_root(a);
int root_b = get_root(b);
if (root_a == root_b) {
// The nodes are already in the same component
return -1;
}
// Otherwise, connect the graphs
if (conex_rank[root_a] < conex_rank[root_b]) {
conex_comp[root_a] = root_b;
} else {
conex_comp[root_b] = root_a;
}
if (conex_rank[root_a] == conex_rank[root_b]) {
++conex_rank[root_b];
}
return 0;
}
int main(void) {
fin >> n >> m;
for (int i = 1; i <= n; ++i) {
conex_comp[i] = i;
conex_rank[i] = 1;
}
for (int i = 0; i < m; ++i) {
int type, src, dest;
fin >> type >> src >> dest;
switch (type) {
case 1:
unite(src, dest);
break;
case 2:
if (get_root(src) == get_root(dest)) {
fout << "DA\n";
} else {
fout << "NU\n";
}
break;
}
}
return 0;
}