Pagini recente » Cod sursa (job #701541) | Cod sursa (job #2147053) | Cod sursa (job #2471737) | Cod sursa (job #2882843) | Cod sursa (job #2944070)
#include <iostream>
#include<fstream>
#include<vector>
using namespace std;
int N,M,operatie,x,y;
vector<int> tata, grad;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int cautare(int nod)
{
if(nod!=tata[nod]) return cautare(tata[nod]);
return nod;
}
void reuniune(int nod1, int nod2)
{
nod1 = cautare(nod1);
nod2 = cautare(nod2);
if(grad[nod1] > grad[nod2])
{
tata[nod2] = nod1;
}
else if(grad[nod1] < grad[nod2])
{
tata[nod1] = nod2;
}
else {
tata[nod2] = nod1;
grad[nod1]++;
}
}
int main()
{
f>>N>>M;
tata.resize(N+1,0);
grad.resize(N+1,0);
for(int i=1;i<=N;i++)
tata[i]=i;
for(int i=1;i<=M;i++)
{
f>>operatie>>x>>y;
if(operatie==1)
{
reuniune(x,y);
}
else if(operatie==2)
{
if (cautare(x)==cautare(y)) g<<"DA"<<'\n';
else g<<"NU"<<'\n';
}
}
}