Pagini recente » Cod sursa (job #2926155) | Istoria paginii runda/oji_bv_1112/clasament | Cod sursa (job #3004643) | Cod sursa (job #3123466) | Cod sursa (job #2500504)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
int t[200005];
int h[200005];
int findSet(int x)
{
while (x != t[x])
x = t[x];
return x;
}
void uniteSet(int x, int y)
{
x = findSet(x);
y = findSet(y);
if (x == y)
return;
if (h[x] == h[y])
{
t[y] = x;
h[x]++;
}
else if (h[x] < h[y])
t[x] = y;
else
t[y] = x;
}
struct edge {
int x, y, c;
};
vector<edge> G, ansEdges;
int n, m, ans;
int main()
{
in >> n >> m;
for (int i = 1; i <= n; i++)
{
t[i] = i;
h[i] = 1;
}
for (int i = 1; i <= m; i++)
{
int x, y, c;
in >> x >> y >> c;
G.push_back({ x, y, c });
}
sort(G.begin(), G.end(), [](const edge& l, const edge& r) { return l.c < r.c; });
for (const edge& e : G)
{
if (findSet(e.x) != findSet(e.y))
{
uniteSet(e.x, e.y);
ans += e.c;
ansEdges.push_back(e);
}
}
out << ans << '\n';
out << ansEdges.size() << '\n';
for (const edge& e : ansEdges)
out << e.x << ' ' << e.y << '\n';
}