Pagini recente » Cod sursa (job #2854515) | Cod sursa (job #1658686) | Cod sursa (job #2160473) | Cod sursa (job #2271204) | Cod sursa (job #2723417)
#include <bits/stdc++.h>
#define Nmax 400005
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m,k, total;
struct Muchie
{
int x, y, cost;
}v[Nmax];
int TT[Nmax], RG[Nmax];
pair <int, int>P[Nmax];
int compare(Muchie a, Muchie b)
{
return a.cost < b.cost;
}
void afisare()
{
fout<<total<<"\n";
fout<<k<<"\n";
for(int i=1; i<=k; i++)
fout<<P[i].first<<" "<<P[i].second<<"\n";
fin.close();
fout.close();
}
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 Find(int nod)
{
while(TT[nod] != nod)
nod = TT[nod];
return nod;
}
void unire(int x, int y)
{
if(RG[x] > RG[y])
TT[y] = x;
if(RG[y] > RG[x])
TT[x] = y;
if(RG[x] == RG[y])
{
TT[x] = y;
RG[y]++;
}
}
void rezolvare()
{
for(int i=1; i<=m; i++)
{
int tatal_x = Find(v[i].x);
int tatal_y = Find(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 += v[i].cost;
}
}
}
int main()
{
citire();
rezolvare();
afisare();
return 0;
}