Pagini recente » Cod sursa (job #862740) | Cod sursa (job #147087) | Cod sursa (job #2032943) | Cod sursa (job #956752) | Cod sursa (job #2192091)
#include <iostream>
#include <fstream>
using namespace std;
class Multime{
private :
int *tata, *h;
public :
explicit Multime(int);
~Multime();
void initialiare(int);
int Reprez(int);
void reuniune(int, int);
};
Multime::Multime(const int n) {
this->tata = new int[n + 1];
this->h = new int[n + 1];
}
Multime::~Multime() {
delete[] tata;
delete[] h;
}
void Multime::initialiare(const int u) {
tata[u] = h[u] = 0;
}
int Multime::Reprez(int u) {
//cu compresie de cale
if(!tata[u])
return u;
tata[u] = Reprez(tata[u]);
return tata[u];
}
void Multime::reuniune(int u, int v) {
int ru = Reprez(u);
int rv = Reprez(v);
if(h[ru] > h[rv])
tata[rv] = ru;
else {
tata[ru] = rv;
if(h[ru] == h[rv])
h[rv]++;
}
}
class Drive{
private :
int *N, *M;
int *choice, *x, *y;
public :
Drive();
~Drive();
void solve();
};
Drive::Drive() {
N = new int;
M = new int;
choice = new int;
x = new int;
y = new int;
}
Drive::~Drive() {
delete N;
delete M;
delete choice;
delete x;
delete y;
}
void Drive::solve() {
ifstream fin("disjoint.in");
if(!fin.is_open()) {
cout << "The file can't be opened!\n";
exit(EXIT_FAILURE);
}
ofstream fout("disjoint.out");
if(!fout.is_open()) {
cout << "The file can't be opened!\n";
exit(EXIT_FAILURE);
}
fin >> *N >> *M;
Multime *disjoint = new Multime(*N);
for(int i = 0; i < *N; ++i)
disjoint->initialiare(i + 1);
for(int i = 0; i < *M; ++i) {
fin >> *choice >> *x >> *y;
switch(*choice) {
case 1 : {
disjoint->reuniune(*x, *y);
break;
}
case 2 : {
if(disjoint->Reprez(*x) == disjoint->Reprez(*y))
fout << "DA\n";
else
fout << "NU\n";
break;
}
}
}
delete disjoint;
fin.close();
fout.close();
}
int main() {
Drive *test = new Drive;
test->solve();
delete test;
return 0;
}