Pagini recente » Cod sursa (job #2316811) | Cod sursa (job #3133324) | Cod sursa (job #3282132) | Cod sursa (job #2892386) | Cod sursa (job #2909986)
#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;
bool disposed;
public:
DSU()
{
disposed = false;
len = 0;
}
int32_t find(int32_t index)
{
jassert(!disposed, "Object was disposed");
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(!disposed, "Object was disposed");
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(!disposed, "Object was disposed");
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 init(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;
disposed = false;
}
void clear()
{
if(disposed)
return;
parent.clear();
rank.clear();
disposed = true;
}
}; // class DSU
} // namespace DSU
using namespace ja::AdvancedDataStructures::DSU;
#include <iostream>
#include <fstream>
std::ifstream cin ("disjoint.in");
std::ofstream cout ("disjoint.out");
int main()
{
std::ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
DSU* dsu = new DSU();
dsu->init(n);
while(m--)
{
int op, a, b;
cin >> op >> a >> b;
a--, b--;
switch(op)
{
case 1:
dsu->merge(a, b);
break;
case 2:
bool ans = dsu->same_set(a,b);
cout << (ans ? "DA" : "NU") << '\n';
break;
}
}
cout.flush();
return 0;
}