Pagini recente » Cod sursa (job #24762) | Cod sursa (job #569208) | Cod sursa (job #535415) | Cod sursa (job #1742093) | Cod sursa (job #1927809)
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie
{
int x, y, c;
};
bool cmpf(muchie a, muchie b)
{
return a.c<b.c;
}
int n, m, t[200001], rg[200001], cost=0, ind[200001];
muchie l[400001];
void citire()
{
int i;
fin>>n>>m;
for(i=1; i<=m; i++)
fin>>l[i].x>>l[i].y>>l[i].c;
fin.close();
}
int gaseste(int x)
{
int r, aux;
r=x;
while(t[r]!=r)
r=t[r];
while(t[x]!=x)
{
aux=t[x];
t[x]=r;
x=aux;
}
return r;
}
void unifica(int x, int y)
{
if(rg[x]>rg[y])
t[y]=x;
else t[x]=y;
if(rg[x]==rg[y])
rg[y]++;
}
void kruskal()
{
int i, k;
for(i=1; i<=n; i++)
{
t[i]=i;
rg[i]=i;
}
k=1;
i=1;
while(k<=n-1 && i<=m)
{
if(gaseste(l[i].x)!=gaseste(l[i].y))
{
cost+=l[i].c;
unifica(gaseste(l[i].x), gaseste(l[i].y));
ind[k]=i;
k++;
}
i++;
}
}
void afisare()
{
fout<<cost<<endl<<n-1<<endl;
for(int i=1; i<=n-1; i++)
fout<<l[ind[i]].x<<' '<<l[ind[i]].y<<'\n';
fout.close();
}
int main()
{
citire();
sort(l+1, l+1+m, cmpf);
kruskal();
afisare();
return 0;
}