Pagini recente » Cod sursa (job #2393397) | Solutii preONI 2007, Runda 1 | Cod sursa (job #1244028) | Cod sursa (job #1040944) | Cod sursa (job #1888031)
#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);
string areInSameSet = (root1==root2) ? "DA" : "NU";
out<<areInSameSet<<'\n';
}
}
in.close();out.close();
return 0;
}
int findRoot(int nod) {
int n = nod;
while (dad[n] != n) {
n = dad[n];
}
int root = n;
while (dad[nod] != nod) {
int tempDad = dad[nod];
dad[nod] = root;
nod = tempDad;
}
return root;
}
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;
}
}