Pagini recente » Cod sursa (job #3120577) | Cod sursa (job #1442369) | Cod sursa (job #2104588) | Cod sursa (job #3326694) | Cod sursa (job #3321803)
#include <cstdint>
#include <fstream>
#include <functional>
#include <vector>
#include <queue>
#define MAX_N 200005
struct Edge {
int to, cost;
Edge(int to, int cost) : to{to}, cost{cost} {}
};
struct PQEdge {
int node, cost, parent;
PQEdge(int node, int cost, int parent = -1) : node{node}, cost{cost}, parent{parent} {}
bool operator>(const PQEdge& other) const
{
return cost > other.cost;
}
};
struct MSTEdge {
int x, y;
};
std::vector<Edge> adj[MAX_N];
bool visited[MAX_N];
int main() {
std::ifstream fin("apm.in");
std::ofstream fout("apm.out");
int n, m;
fin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v, cost;
fin >> u >> v >> cost;
adj[u].push_back(Edge(v, cost));
adj[v].push_back(Edge(u, cost));
}
std::priority_queue<PQEdge, std::vector<PQEdge>, std::greater<PQEdge>> pq;
std::vector<MSTEdge> mst_edges;
intmax_t total_cost = 0;
pq.push(PQEdge(1, 0));
while (!pq.empty()) {
auto current = pq.top();
pq.pop();
if (visited[current.node]) {
continue;
}
visited[current.node] = true;
total_cost += current.cost;
if (current.parent != -1) {
mst_edges.push_back({current.parent, current.node});
}
for (auto e : adj[current.node]) {
if (!visited[e.to]) {
pq.push(PQEdge(e.to, e.cost, current.node));
}
}
}
fout << total_cost << "\n";
fout << mst_edges.size() << "\n";
for (auto e : mst_edges) {
fout << e.x << " " << e.y << "\n";
}
}