Pagini recente » Cod sursa (job #1159062) | Cod sursa (job #1485690) | Cod sursa (job #746580) | Cod sursa (job #1617820) | Cod sursa (job #2909958)
#include <vector>
#include <cstdint>
#include <cassert>
namespace ja::AdvancedDataStructures::DSU
{
#ifndef jassert
#define jassert(expr, msg, ...) assert(expr && msg)
#endif // jassert
#ifndef jlog
#define jlog(...) ((void)0)
#endif // jlog
class DSU
{
private:
std::vector<int32_t> parent, rank;
int32_t len;
public:
DSU(int32_t length)
{
len = length;
parent = std::vector<int32_t>(len);
rank = std::vector<int32_t>(len, 0);
for(int32_t i = 0; i < len; i++)
parent[i] = i;
}
int32_t find(int32_t index)
{
jassert(0 <= index && index <= len, "Index is outside of bounds", index);
int32_t root = index, temp;
while(parent[root] != root)
root = parent[root];
while(parent[index] != root) {
temp = parent[index];
parent[index] = root;
index = temp;
}
return root;
}
void merge(int32_t first, int32_t second)
{
jassert(0 <= first && first <= len, "Index is outside of bounds", first);
jassert(0 <= second && second <= len, "Index is outside of bounds", second);
first = find(first);
second = find(second);
if(first == second)
return;
if(rank[first] < rank[second])
std::swap(first, second);
parent[second] = first;
if(rank[first] == rank[second])
rank[first]++;
}
bool same_set(int32_t first, int32_t second)
{
jassert(0 <= first && first <= len, "Index is outside of bounds", first);
jassert(0 <= second && second <= len, "Index is outside of bounds", second);
return find(first) == find(second);
}
void clear()
{
parent.clear();
rank.clear();
}
}; // class DSU
} // namespace DSU
using namespace ja::AdvancedDataStructures::DSU;
#include <iostream>
int main()
{
int n, m;
std::cin >> n >> m;
DSU* dsu = new DSU(n);
while(m--)
{
int op, a, b;
std::cin >> op >> a >> b;
a--, b--;
switch(op)
{
case 1:
dsu->merge(a, b);
break;
case 2:
bool ans = dsu->same_set(a,b);
std::cout << (ans ? "DA" : "NU") << '\n';
break;
}
}
std::cout.flush();
return 0;
}