Pagini recente » Cod sursa (job #2323016) | Cod sursa (job #926374) | Cod sursa (job #65203) | Cod sursa (job #1821455) | Cod sursa (job #3250619)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
struct DSU
{
int N;
vector<int> parent;
void dsuinit(int n)
{
N = n;
parent.resize(N + 1);
int i;
for(i = 1; i <= N; i++)
parent[i] = 0;
}
int get_root(int node)
{
int aux = node;
while(parent[node] > 0)
node = parent[node];
int root = node;
node = aux;
while (node != root)
{
aux = parent[node];
parent[node] = root;
node = aux;
}
return root;
}
void join(int x, int y)
{
int rootx = get_root(x);
int rooty = get_root(y);
if(rootx == rooty)
return;
if(parent[rootx] < parent[rooty])
{
parent[rootx] += parent[rooty];
parent[rooty] = rootx;
}
else
{
parent[rooty] += parent[rootx];
parent[rootx] = rooty;
}
}
bool query(int x, int y)
{
return get_root(x) == get_root(y);
}
};
int main()
{
DSU dsu;
int n, m;
cin >> n >> m;
dsu.dsuinit(n);
int i, type, x, y;
for(i = 0; i < m; i++)
{
cin >> type >> x >> y;
if(type == 1)
{
dsu.join(x, y);
}
else
{
cout << (dsu.query(x, y) ? "DA\n" : "NU\n");
}
}
}