Pagini recente » Cod sursa (job #2214147) | Cod sursa (job #2741490) | Cod sursa (job #836636) | Cod sursa (job #505596) | Cod sursa (job #1024880)
#include <fstream>
#include <algorithm>
#include <vector>
#define nmax 100000+5
#define mmax 400000+5
#define FOR(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;
struct muchie
{
int x, y, cost;
};
ifstream fin("apm.in");
ofstream fout("apm.out");
int tata[nmax];
int h[nmax];
int n, m;
muchie u[mmax];
int costAPM;
vector<muchie> afis;
int radacina(int x)
{
int r = x, t;
while (r != tata[r])
r = tata[r];
while (x != tata[x])
{
t = tata[x];
tata[x] = r;
x = t;
}
return r;
}
void link(int x, int y)
{
int sx = radacina(x);
int sy = radacina(y);
if (h[sx] < h[sy])
tata[sx] = sy;
else if (h[sx] > h[sy])
tata[sy] = sx;
else
{
tata[sx] = sy;
h[sy]++;
}
}
int conectat(int x, int y)
{
return (radacina(x) == radacina(y));
}
void citire()
{
fin >> n >> m;
FOR(i, 1, m)
fin >> u[i].x >> u[i].y >> u[i].cost;
}
int cmp(muchie a, muchie b)
{
return a.cost < b.cost;
}
void kruscal()
{
int cnt = 0;
FOR(i, 1, n)
tata[i] = i;
sort(u+1,u+m+1,cmp);
FOR(j, 1, m)
{
if (cnt == n-1)
break;
if (!conectat(u[j].x, u[j].y))
{
costAPM += u[j].cost;
link(u[j].x, u[j].y);
afis.push_back(u[j]);
cnt++;
}
}
}
void afisare()
{
fout << costAPM << '\n';
fout << n-1 << '\n';
if (!afis.empty())
FOR(i, 0, afis.size()-1)
fout << afis[i].x << ' ' << afis[i].y << '\n';
}
int main()
{
citire();
kruscal();
afisare();
return 0;
}