Pagini recente » Cod sursa (job #2417368) | Cod sursa (job #2417372) | Cod sursa (job #2417725) | Cod sursa (job #2085345) | Cod sursa (job #2417852)
#include <bits/stdc++.h>
struct Edge {
int from, to, cost;
};
int root(std::vector<int>& P, int x) {
int y = x;
while (x != P[x]) {
x = P[x];
}
while (P[y] != x) {
int aux = P[y];
P[y] = x;
y = aux;
}
return x;
}
int main() {
std::ifstream f("apm.in");
int V, E;
f >> V >> E;
std::vector<Edge> Graph(E);
for (int i = 0; i < E; i++) {
int x, y, w;
f >> x >> y >> w;
Graph[i] = Edge {--x, --y, w};
}
f.close();
std::sort(Graph.begin(), Graph.end(), [] (Edge& a, Edge& b) {return a.cost < b.cost;});
std::vector<int> P(V);
std::vector<std::pair<int, int>> res(V - 1);
for (size_t i = 0; i < P.size(); i++) {
P[i] = i;
}
int k = 0;
int cost = 0;
for (int i = 0; i < E && k < V - 1; i++) {
int x = root(P, Graph[i].from);
int y = root(P, Graph[i].to);
if (x == y) continue;
res[k++] = {Graph[i].from, Graph[i].to};
P[x] = y;
cost += Graph[i].cost;
}
std::ofstream g("apm.out");
g << cost << '\n' << res.size() << '\n';
for (size_t i = 0; i < res.size(); i++) {
g << res[i].first << ' ' << res[i].second << '\n';
}
g.close();
return 0;
}