Pagini recente » Cod sursa (job #1004975) | Cod sursa (job #1200906) | Cod sursa (job #1258213) | Cod sursa (job #1501199) | Cod sursa (job #1999126)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <map>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
bool v[400001];
struct muchie{
int first,second;
int cost;
}cost[400001];
int t[200001],h[200001];
int findset(int x){
while(x!=t[x])
x=t[x];
return x;
}
bool unionset(int x,int y){
int tx=findset(x),ty=findset(y);
if(tx==ty)return 0;
if(h[tx]==h[ty]){
h[tx]++;
t[ty]=tx;
}
else
if(h[tx]<=h[ty])
t[tx]=ty;
else
t[ty]=tx;
return 1;
}
bool cmp(muchie a,muchie b){
return (a.cost<b.cost);
}
int main()
{
int n,m,a,b,c,costy=0,nr=0;
in>>n>>m;
for(int i=1;i<=m;i++){
in>>cost[i].first>>cost[i].second>>cost[i].cost;
}
for(int i=1;i<=n;i++)
h[i]=1,t[i]=i;
sort(cost+1,cost+m+1,cmp);
for(int i=1;i<=m;i++){
if(nr==n-1){
out<<n-1<<endl<<costy<<endl;
for(int j=1;j<=m;j++)
if(v[j]==1)
out<<cost[j].first<<" "<<cost[j].second<<endl;
return 0;
}
if(nr<=n-1)
if(unionset(cost[i].first,cost[i].second)==1)
nr++,costy+=cost[i].cost,v[i]=1;
}
out<<costy;
return 0;
}