Pagini recente » Cod sursa (job #2763444) | Cod sursa (job #1322371) | Cod sursa (job #1657175) | Cod sursa (job #470757) | Cod sursa (job #3305235)
#include <fstream>
#include <algorithm>
#define NMAX 200002
#define MMAX 400002
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int N,M,ans,cnt,rad[NMAX],nr[NMAX];
struct muchie
{
int x,y,c;
}v[MMAX];
struct solutie
{
int x,y;
}sol[MMAX];
void citire()
{
fin>>N>>M;
for(int i=1; i<=M; i++)
{
fin>>v[i].x>>v[i].y>>v[i].c;
}
}
bool cmp(muchie a, muchie b)
{
return a.c<b.c;
}
int Find(int x)
{
if(x==rad[x])
{
return x;
}
else
{
rad[x]=Find(rad[x]);
return rad[x];
}
}
void Union(int a, int b)
{
if(nr[a]>=nr[b])
{
rad[b]=a;
nr[a]+=nr[b];
}
else
{
rad[a]=b;
nr[b]+=nr[a];
}
}
int main()
{
citire();
for(int i=1; i<=N; i++)
{
rad[i]=i;
nr[i]=1;
}
sort(v+1,v+1+M,cmp);
ans=cnt=0;
for(int i=1; i<=M; i++)
{
int x,y;
x=Find(v[i].x);
y=Find(v[i].y);
if(x!=y)
{
Union(x,y);
ans+=v[i].c;
cnt++;
sol[cnt].x=v[i].x;
sol[cnt].y=v[i].y;
}
}
fout<< ans << "\n";
fout<< cnt << "\n";
for(int i=1; i<=cnt; i++)
{
fout<< sol[i].x << " " << sol[i].y << "\n";
}
return 0;
}