Pagini recente » Cod sursa (job #2705642) | Cod sursa (job #2507293) | Cod sursa (job #1442186) | Cod sursa (job #1414677) | Cod sursa (job #3183850)
#include <iostream>
#include <fstream>
#define FIN "disjoint.in"
#define FOUT "disjoint.out"
typedef unsigned int uint;
typedef unsigned long ulong;
using namespace std;
class UnionFind {
public:
//constructor of the class
UnionFind(uint n):nElements(n), parent( new ulong[n+1] ), rank( new ulong[n+1] ) {
for(int i = 1; i <= nElements; ++i) {
parent[ i ] = i;
rank[ i ] = 1;
}
};
void unionSets(ulong x, ulong y) {
ulong rootX = getRoot( x ),
rootY = getRoot( y );
if(rank[ rootX ] > rank[ rootY ]) {
parent[ rootY ] = rootX;
} else if(rank[ rootX ] < rank[ rootY ]) {
parent[ rootX ] = rootY;
} else {
parent[ rootY ] = rootX;
rank[ rootY ]++;
}
}
ulong sameSets(ulong x, ulong y) {
ulong rootX = getRoot( x ),
rootY = getRoot( y );
return rootX == rootY;
}
//destructor of the class
~UnionFind() {
delete [] parent;
delete [] rank;
}
private:
uint nElements;
ulong *parent,
*rank;
ulong getRoot( ulong node ) {
ulong root = parent[ node ];
while(root != parent[root]) {
root = parent[root];
}
return root;
}
};
int main(int argc, char const *argv[]) {
ulong numElements, numOps, type, x, y;
ifstream fin( FIN );
ofstream fout( FOUT );
if(!fin) {
cout<<"Error opening the file";
return -1;
}
if(!fout) {
cout<<"Error opening and writing the file";
return -1;
}
fin>>numElements>>numOps;
UnionFind forest( numElements );
while( numOps-- ) {
fin>>type>>x>>y;
switch(type) {
case 1:
forest.unionSets(x, y);
break;
case 2:
fout<< (forest.sameSets(x, y) ? "DA":"NU")<<"\n";
break;
}
}
return 0;
}