Pagini recente » Cod sursa (job #2071125) | Cod sursa (job #5555) | Cod sursa (job #1495453) | Cod sursa (job #3255256) | Cod sursa (job #2934615)
#include <fstream>
#include <iostream>
using namespace std;
template <typename T>
class DisjointForest{
private:
const unsigned int _size;
T* _father;
T getRoot(T el){
while(_father[el - 1] != el){
el = _father[el - 1];
}
return el;
}
public:
DisjointForest(const unsigned int p_size) : _size(p_size){
_father = new T[p_size];
for(unsigned int i = 0; i<p_size;++i){
_father[i] = i + 1;
}
}
void merge(const T x, const T y){
_father[getRoot(y) - 1] = getRoot(x);
}
bool check(const T x, const T y){
return getRoot(x) == getRoot(y);
}
~DisjointForest(){
delete[] _father;
}
};
int main(){
ifstream in("disjoint.in");
ofstream out("disjoint.out");
unsigned int n, m;
in >> n >> m;
DisjointForest<unsigned int> forest(n);
for(unsigned int i=0; i<m; ++i){
unsigned int cmd, x, y;
in >> cmd >> x >> y;
switch(cmd)
{
case 1:
forest.merge(x, y);
break;
case 2:
out << (forest.check(x, y) ? "DA\n" : "NU\n");
break;
default:
break;
}
}
in.close();
out.close();
}