Pagini recente » Monitorul de evaluare | Cod sursa (job #3357826) | Cod sursa (job #3357870) | Cod sursa (job #3357858) | Cod sursa (job #3357813)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
int main() {
std::ifstream input("apm.in");
std::ofstream output("apm.out");
int n, m;
input >> n >> m;
std::vector<std::vector<std::pair<int, int>>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int x, y, c;
input >> x >> y >> c;
graph[x].emplace_back(y, c);
graph[y].emplace_back(x, c);
}
std::vector<bool> in_apm(n + 1, false);
auto cmp = [](const std::pair<int, int> &lhs, const std::pair<int, int> &rhs) {
return lhs.second > rhs.second;
};
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, decltype(cmp)> pq(cmp);
std::vector<long long> dist(n + 1, LLONG_MAX);
std::vector<int> parent(n + 1, 0);
dist[1] = 0;
pq.emplace(1, 0);
while (!pq.empty()) {
int u = pq.top().first;
pq.pop();
if (in_apm[u]) continue;
in_apm[u] = true;
for (const auto &edge : graph[u]) {
int v = edge.first;
int weight = edge.second;
if (!in_apm[v] && weight < dist[v]) {
dist[v] = weight;
parent[v] = u;
pq.emplace(v, weight);
}
}
}
long long total_cost = 0;
for (int i = 1; i <= n; ++i) {
if (dist[i] != LLONG_MAX) {
total_cost += dist[i];
}
}
output << total_cost << '\n';
output << n - 1 << '\n';
for (int i = 2; i <= n; ++i) {
output << i << " " << parent[i] << '\n';
}
return 0;
}