Pagini recente » Cod sursa (job #3243488) | Cod sursa (job #2482211) | Cod sursa (job #2322999) | Cod sursa (job #714434) | Cod sursa (job #3220625)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
class DisjointSets
{
public:
vector<int> father, setsize;
DisjointSets();
DisjointSets(int n);
void unite(int x, int y);
int find(int x);
};
int main()
{
int n, q;
fin >> n >> q;
DisjointSets ds(n + 1);
for(int i = 0; i < q; i++)
{
int type, x, y;
fin >> type >> x >> y;
if(type == 1)
{
ds.unite(x, y);
}
else
{
if(ds.find(x) == ds.find(y))
{
fout << "DA\n";
}
else
{
fout << "NU\n";
}
}
}
return 0;
}
DisjointSets::DisjointSets()
{
}
DisjointSets::DisjointSets(int n)
{
this->father = vector<int>(n, -1);
this->setsize = vector<int>(n, 1);
}
void DisjointSets::unite(int x, int y)
{
int xRep, yRep;
xRep = this->find(x);
yRep = this->find(y);
if(this->setsize[yRep] < this->setsize[xRep])
{
this->setsize[xRep] += this->setsize[yRep];
this->setsize[yRep] = this->setsize[xRep];
this->father[yRep] = xRep;
}
else
{
this->setsize[yRep] += this->setsize[xRep];
this->setsize[xRep] = this->setsize[yRep];
this->father[xRep] = yRep;
}
}
int DisjointSets::find(int x)
{
if(this->father[x] == -1)
return x;
int representative;
representative = this->find(father[x]);
this->father[x] = representative;
return representative;
}