Pagini recente » Cod sursa (job #2072584) | Cod sursa (job #2616564) | Cod sursa (job #2973263) | Cod sursa (job #420918) | Cod sursa (job #1511769)
#include <fstream>
#include <vector>
using namespace std;
int query(vector<int>& root, int x) {
int curr = x;
while(root[curr] != curr) {
curr = root[curr];
}
root[x] = curr;
return root[x];
}
void unite(vector<int>& root, vector<int>& rang, int x, int y) {
int rootX, rootY;
rootX = query(root, x);
rootY = query(root, y);
if(rang[rootX] == rang[rootY]) {
root[rootX] = rootY;
++rang[rootY];
}
if(rang[rootX] < rang[rootY]) {
root[rootX] = rootY;
}
if(rang[rootX] > rang[rootY]) {
root[rootY] = rootX;
}
}
int main() {
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int N, M;
fin >> N >> M;
vector<int> root(N);
vector<int> rang(N, 1);
for(int i=0; i<N; ++i) {
root[i] = i;
}
int a, b, c;
for(int i=0; i<M; ++i) {
fin >> a >> b >> c;
if(a == 1) {
unite(root, rang, b-1, c-1);
}
if(a == 2) {
if(query(root, b-1) == query(root, c-1))
fout << "DA\n";
else
fout << "NU\n";
}
}
return 0;
}