Pagini recente » Cod sursa (job #681725) | Cod sursa (job #616547) | Cod sursa (job #2825219) | Cod sursa (job #198063) | Cod sursa (job #3030211)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m, i, j, x, y, nm, p[200001], r[200001], c, cost;
struct muchie
{
int x, y;
short c;
};
vector <muchie> g, sol;
int root (int x)
{
while (r[x] != x)
x = r[x];
return x;
}
bool comp (muchie a, muchie b)
{
return a.c < b.c;
}
int merger (int x, int y)
{
if (p[x] < p[y])
r[x] = y;
else if (p[x] > p[y])
r[y] = x;
else if (p[x] == p[y])
{
r[y] = x;
p[x]++;
}
}
int main()
{
fin >> n >> m;
for (i = 1; i <= n; i++)
r[i] = i;
for (i = 1; i <= m; i++)
{
fin >> x >> y >> c;
g.push_back({x, y, c});
}
sort (g.begin(), g.end(), comp);
i = 0;
while (nm < n-1)
{
x = g[i].x; y = g[i].y;
int rx = root(x), ry = root(y);
if (rx != ry)
{
merger(rx, ry);
nm++;
sol.push_back(g[i]);
cost += g[i].c;
}
i++;
}
fout << cost << '\n' << n-1 << '\n';
for (auto it : sol)
{
fout << it.y << ' ' << it.x << '\n';
}
return 0;
}