Pagini recente » Cod sursa (job #2656611) | Cod sursa (job #505107) | Cod sursa (job #515505) | Cod sursa (job #1931703) | Cod sursa (job #2411260)
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
#define nmax 400005
struct apm
{
int x,y,cost;
}v[nmax];
pair <int,int> P[nmax];
bool comp(apm a, apm b)
{
return a.cost<b.cost;
}
int t[nmax],rg[nmax],n,m,cont=0,Cost=0;
int Find(int nod)
{
while(nod!=t[nod])
nod=t[nod];
return nod;
}
void Union(int x, int y)
{
if(rg[x]<rg[y])
t[x]=y;
if(rg[y]<rg[x])
t[y]=x;
if(rg[x]==rg[y])
{
t[x]=y;
rg[y]++;
}
}
void Sol()
{
for(int i=1;i<=m;i++)
{
if(Find(v[i].x)!=Find(v[i].y))
{
Union(Find(v[i].x),Find(v[i].y));
Cost+=v[i].cost;
cont++;
P[cont].first=v[i].y;
P[cont].second=v[i].x;
}
}
}
int main()
{
fin>>n>>m;
for(int i=1;i<=m;i++)
fin>>v[i].x>>v[i].y>>v[i].cost;
for(int i=1;i<=n;i++)
{
t[i]=i;
rg[i]=1;
}
sort(v+1,v+1+m,comp);
Sol();
fout<<Cost<<'\n';
fout<<cont<<'\n';
for(int i=1;i<=cont;i++)
fout<<P[i].first<<" "<<P[i].second<<'\n';
}