Pagini recente » Cod sursa (job #1017496) | Borderou de evaluare (job #1560399) | Cod sursa (job #3327387) | Cod sursa (job #3358426) | Cod sursa (job #3358485)
// Disjoint Set Union
//
// Graph data structure that provides the following operations:
// - union -> union two sets together
// - find -> for two different nodes, find if they are in the same strongly
// connected component
//
// Complexity: almost O(1)
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> parent;
vector<int> depth;
void make_set(int node)
{
parent[node] = node;
depth[node] = 0;
}
int find_set(int node)
{
if (node == parent[node])
return node;
return parent[node] = find_set(parent[node]);
}
void union_sets(int node1, int node2)
{
int p1 = find_set(node1);
int p2 = find_set(node2);
if (p1 == p2)
return;
if (depth[p1] < depth[p2])
swap(p1, p2);
if (depth[p1] == depth[p2])
depth[p1]++;
parent[p2] = p1;
}
int main()
{
freopen("disjoin.in", "r", stdin);
freopen("disjoin.out", "w", stdout);
cin >> n >> m;
parent.resize(n);
depth.resize(n);
for (int i = 0; i < n; i++)
make_set(i);
for (int i = 0; i < m; i++) {
int op, x, y;
cin >> op >> x >> y;
if (op == 1) {
union_sets(x, y);
} else {
cout << (find_set(x) == find_set(y) ? "DA\n" : "NU\n");
}
}
return 0;
}