Pagini recente » Cod sursa (job #3292411) | Cod sursa (job #815604) | Cod sursa (job #558594) | Cod sursa (job #1750061) | Cod sursa (job #2120193)
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
#define mmax 400005
#define nmax 200005
struct muchie
{
int x, y, c;
};
muchie L[mmax];
bool cmpf(muchie a, muchie b)
{
return a.c<b.c;
}
int n, m, rang[nmax], t[nmax], index[nmax], cost;
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();
}
void uneste(int x, int y)
{
if(rang[x]<rang[y])
t[x]=y;
else t[y]=x;
}
int radacina(int x)
{
int r, aux;
r=x;
while(r!=t[r])
r=t[r];
while(x!=t[x])
{
aux=t[x];
t[x]=r;
x=aux;
}
return r;
}
void Kruskal()
{
int i, k;
sort(L+1, L+1+m, cmpf);
for(i=1; i<=n; i++)
rang[i]=t[i]=i;
i=k=1;
while(i<=m && k<=n-1)
{
if(radacina(L[i].x)!=radacina(L[i].y))
{
uneste(radacina(L[i].x), radacina(L[i].y));
cost+=L[i].c;
index[k]=i;
k++;
}
i++;
}
}
void afisare()
{
int i;
fout<<cost<<'\n'<<n-1<<'\n';
for(i=1; i<=n-1; i++)
fout<<L[index[i]].x<<' '<<L[index[i]].y<<'\n';
fout.close();
}
int main()
{
citire();
Kruskal();
afisare();
return 0;
}