Pagini recente » Cod sursa (job #1908921) | Cod sursa (job #2266467) | Cod sursa (job #462139) | Cod sursa (job #1767242) | Cod sursa (job #2937176)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
vector<int>tata(100001);
vector<int>rang(100001);
int n, m, operatie, x, y;
int reprezentant(int nod){ //reprezinta radacina unei componente conexe
int n1 = nod;
while(tata[nod] != nod){
nod=tata[nod];
}
while(n1 != nod){ //unim toate nodurile dintr-o componenta conexa de radacina
int n2 = tata[n1];
tata[n1] = nod;
n1 = n2;
}
return nod;
}
void reuniune(int x, int y){
int reprezentant_x = reprezentant(x), reprezentant_y = reprezentant(y);
//aleg ca tata reprezentantul care are rangul mai mare
if(rang[reprezentant_x] < rang[reprezentant_y])
tata[reprezentant_x] = reprezentant_y;//leg reprezentantul lui x direct de reprezentantul lui y(radacina componentei conexe care-l contine pe y)
else{
tata[reprezentant_y] = reprezentant_x;//leg reprezentantul lui y direct de reprezentantul lui x(radacina componentei conexe care-l contine pe x)
if (rang[reprezentant_x] == rang[reprezentant_y]) //daca rangurile sunt egale aleg sa l cresc pe cel al reprezentantului lui y
rang[reprezentant_y]++;
}
}
int main() {
fin>>n>>m;
for(int i=1; i<=n; i++)
tata[i]=i, rang[i]=1;
for(int i=0; i<m; i++){
fin>>operatie>>x>>y;
if(operatie==1)
reuniune(x, y);
else{
if(reprezentant(x) == reprezentant(y)) fout << "DA\n";
else fout<<"NU\n";
}
}
for(int i=1; i<=n; i++)
cout<<rang[i]<< " ";
return 0;
}