Pagini recente » Cod sursa (job #3322422) | Cod sursa (job #3297876) | Cod sursa (job #949333) | Cod sursa (job #517644) | Cod sursa (job #3332941)
// https://www.infoarena.ro/problema/apm - Szücs Patrik - Kevin
#include <fstream>
#include <vector>
#include <algorithm>
#define vint std::vector<int>
struct edge
{
int x, y, cost;
bool operator<(const edge &a)
{
return cost < a.cost;
}
};
int find(int x, vint &parent)
{
while (parent[x] != x)
x = parent[x];
return x;
}
int main()
{
int n, m;
std::ifstream in("apm.in");
in >> n >> m;
std::vector<edge> edges;
while (m--)
{
int x, y, c;
in >> x >> y >> c;
edges.push_back({x, y, c});
}
in.close();
sort(edges.begin(), edges.end());
vint parent(n + 1), size(n + 1, 1);
for (int i = 1; i <= n; i++)
parent[i] = i;
std::vector<std::pair<int, int>> ans;
int s = 0;
for (edge &i : edges)
{
int px = find(i.x, parent), py = find(i.y, parent);
if (px != py)
{
if (size[px] < size[py])
std::swap(i.x, i.y);
parent[py] = px;
size[px] += size[py];
s += i.cost;
ans.push_back({i.x, i.y});
}
}
std::ofstream out("apm.out");
out << s << '\n'
<< ans.size();
for (auto &i : ans)
out << '\n'
<< i.first << ' ' << i.second;
return 0;
}