Pagini recente » Cod sursa (job #1767316) | Cod sursa (job #1807594) | Cod sursa (job #1641830) | Cod sursa (job #2223062) | Cod sursa (job #1888057)
#include<iostream>
#include<fstream>
#include<cmath>
#include<algorithm>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
const int NMax = 100000 + 5;
// sets are represented as trees
int N,M;
int dad[NMax],height[NMax];
// dad[i] = the father node of node i in its tree
// height[i] = the (maximum) height of the tree that has node i in it (it may decrease)
int findRoot(int);
void uniteSets(int,int);
// findRoot(x) finds the root of the tree node x is in and updates the root of all the nodes on the path
// uniteSets(x,y) adds the tree with the smallest height to the tree with the biggest height
// (from the two trees that contain x and y) and updates the height of the bigger tree
// (which can only increase when they have the same height)
int main() {
in>>N>>M;
for (int i=1;i<=N;++i) {
dad[i] = i;
height[i] = 1;
}
for (int i=1;i<=M;++i) {
int cod,x,y;
in>>cod>>x>>y;
if (cod==1) {
uniteSets(x,y);
}
else {
int root1 = findRoot(x),
root2 = findRoot(y);
if (root1==root2) {
out<<"DA\n";
}
else {
out<<"NU\n";
}
}
}
in.close();out.close();
return 0;
}
int findRoot(int nod) {
if (dad[nod] == nod) {
return nod;
}
dad[nod] = findRoot(dad[nod]);
return dad[nod];
}
void uniteSets(int x,int y) {
int root1 = findRoot(x),
root2 = findRoot(y);
if (height[root1]>=height[root2]) {
if (height[root1]==height[root2]) {
++height[root1];
}
dad[root2] = root1;
}
else {
dad[root1] = root2;
}
}