Pagini recente » Cod sursa (job #375646) | Cod sursa (job #1593092) | Cod sursa (job #1247157) | Cod sursa (job #1631543) | Cod sursa (job #703479)
Cod sursa(job #703479)
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
struct muchie{
int x,y,c;
};
typedef muchie* pm;
muchie vm[400001],h[200000];
int n,m,ct;
int t[200000];
int g[200000];
int fcmp(void const *a,void const *b){
return ((pm)a)->c-((pm)b)->c;
}
void citire(){
in>>n>>m;
int i;
for(i=1;i<=m;i++)
in>>vm[i].x>>vm[i].y>>vm[i].c;
}
int Find(int x){
if(!t[x]) return x;
return Find(t[x]);
}
void Union(int x, int y){
int tx=Find(x),ty=Find(y);
if(g[tx]<g[ty]) t[tx]=ty;
else{t[ty]=tx;
if(g[tx]==g[ty])
g[tx]++;
}
}
void apm(){
int i;
qsort(vm+1,m,sizeof(vm[0]),fcmp);
int mrel=0;
i=1;
while(mrel<n-1){
int rx=Find(vm[i].x),ry=Find(vm[i].y);
while(rx==ry){ i++;
rx=Find(vm[i].x),ry=Find(vm[i].y);
}
mrel++;
h[mrel]=vm[i];
Union(rx,ry);
ct+=vm[i].c;
}
}
int main(){
citire();
apm();
out<<ct<<"\n"<<n-1<<"\n";
for(int i=1;i<n;i++)
out<<h[i].y<<" "<<h[i].x<<"\n";
}