Pagini recente » Cod sursa (job #640990) | Cod sursa (job #3184233) | Cod sursa (job #3335308) | Cod sursa (job #27442) | Cod sursa (job #3344567)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
const int lim=400001;
pair <int,int> P[lim];
int k;
int N,M, total, tt[lim], rg[lim];
struct muchie
{
int x,y,cost;
}v[lim];
bool compare(muchie a, muchie b)
{
return a.cost<b.cost;
}
void citire()
{
fin>>N>>M;
for (int i=1; i<=M; i++)
fin>>v[i].x>>v[i].y>>v[i].cost;
sort(v+1, v+M+1, compare);
for (int i=1; i<=N; i++)
{
tt[i]=i;
rg[i]=1;
}
}
int gaseste(int nod)
{
while (tt[nod]!=nod)
{
nod=tt[nod];
}
return nod;
}
void unire(int x,int y)
{
if (rg[x]<rg[y])
tt[x]=y;
if (rg[x]>rg[y])
tt[y]=x;
if (rg[x]==rg[y])
{
tt[x]=y;
rg[y]++;
}
}
void rezolva()
{
for (int i=1; i<=N; i++)
{
int tatal_x=gaseste(v[i].x);
int tatal_y=gaseste(v[i].y);
if (tatal_x!=tatal_y)
{
unire(tatal_x, tatal_y);
k++;
P[k++].first=v[i].x;
P[k].second=v[i].y;
total=total+v[i].cost;
}
}
}
void afisare()
{
fout<<total<<"\n";
fout<<N-1<<"\n";
for(int i=1; i<=k; i++)
fout<<P[i].first<<" "<<P[i].second<<"\n";
}
int main()
{
citire();
rezolva();
afisare();
return 0;
}