Pagini recente » Cod sursa (job #2097072) | Istoria paginii runda/ccex2015-9/clasament | Istoria paginii runda/simulare19/clasament | Cod sursa (job #41192) | Cod sursa (job #742684)
Cod sursa(job #742684)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
int *E1, *E2, *EC, *Ei, *ES, *NP, *NR;
bool compara(int a, int b){
return EC[a]<EC[b];
}
int gaseste(int i){
if(NP[i]==i)
return i;
return gaseste(NP[i]);
}
inline void uneste(int x, int y){
int xRoot=gaseste(x);
int yRoot=gaseste(y);
if(xRoot==yRoot)
return;
if(NR[xRoot] < NR[yRoot])
NP[xRoot]=yRoot;
else if(NR[xRoot] > NR[yRoot])
NP[yRoot]=xRoot;
else{
NP[yRoot]=xRoot;
NR[xRoot]++;
}
}
int main(){
int n, m, i, msel=0;
long long sum=0;
{//citire
ifstream fp("apm.in");
fp>>n>>m;
E1=new int[m];
E2=new int[m];
EC=new int[m];
Ei=new int[m];
ES=new int[n-1];
for(i=0; i<m; i++){
fp>>E1[i]>>E2[i]>>EC[i];
Ei[i]=i;
}
fp.close();
}
{//Kruskal
NP=new int[n+1];
NR=new int[n+1];
for(i=1; i<=n; i++){
NP[i]=i;
NR[i]=0;
}
sort(Ei, Ei+m, compara);
for(i=0; i<m; i++)
if(gaseste(E1[Ei[i]]) != gaseste(E2[Ei[i]])){
ES[msel++]=Ei[i];
sum+=EC[Ei[i]];
if(msel==n-1)
break;
uneste(E1[Ei[i]], E2[Ei[i]]);
}
}
{//afisare
ofstream fp("apm.out");
fp<<sum<<endl<<msel<<endl;
for(i=0; i<msel; i++)
fp<<E1[ES[i]]<<" "<<E2[ES[i]]<<endl;
}
return 0;
}