Pagini recente » Cod sursa (job #70269) | Cod sursa (job #2207775) | Cod sursa (job #2313971) | Cod sursa (job #1969495) | Cod sursa (job #2791039)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
vector <int> t, h;
int n, m;
void init() {
h = vector <int> (n + 1);
t = vector <int> (n + 1);
for(int i = 1; i <= n; ++i)
t[i] = i;
}
int getRoot(int node) {
if(node == t[node])
return node;
return (t[node] = getRoot(t[node]));
}
bool sameConnectedComponents(int x, int y) {
return getRoot(x) == getRoot(y);
}
void unite(int x, int y) {
int rootX = getRoot(x);
int rootY = getRoot(y);
if(rootX == rootY)
return;
if(h[rootX] < h[rootY])
t[rootX] = rootY;
else {
if(h[rootX] == h[rootY])
++h[rootX];
t[rootY] = rootX;
}
}
void solve() {
f >> n >> m;
init();
int op, x, y;
for(int i = 1; i <= m; ++i) {
f >> op >> x >> y;
if(op == 1)
unite(x, y);
else g << (sameConnectedComponents(x, y) ? "DA\n" : "NU\n");
}
}
int main()
{
solve();
}