Pagini recente » Cod sursa (job #749640) | Cod sursa (job #2668433) | Cod sursa (job #824476) | Cod sursa (job #825638) | Cod sursa (job #2716968)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int n, m;
vector <int> t, h;
void init() {
t = vector <int> (n + 1);
h = vector <int> (n + 1, 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(sameConnectedComponents(x, y))
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 {
if(sameConnectedComponents(x, y))
g << "DA" << "\n";
else g << "NU" << "\n";
}
}
}
int main()
{
solve();
return 0;
}