Pagini recente » Cod sursa (job #1913788) | Cod sursa (job #747491) | Cod sursa (job #3003585) | Cod sursa (job #1969328) | Cod sursa (job #3271342)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
void primsAlgorithm(vector<vector<pair<int, int>>>& graph, int n, int start = 1)
{
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
vector<bool> visited(n + 1, false);
vector<int> key(n + 1, 1e9);
vector<int> parent(n + 1, -1);
key[start] = 0;
pq.emplace(0, start);
int total_cost = 0;
while (!pq.empty())
{
int node = pq.top().second;
int weight = pq.top().first;
pq.pop();
if (visited[node])
continue;
visited[node] = true;
total_cost += weight;
for (auto& neighbor : graph[node])
{
int adjNode = neighbor.first;
int edgeWeight = neighbor.second;
if (!visited[adjNode] && edgeWeight < key[adjNode])
{
key[adjNode] = edgeWeight;
parent[adjNode] = node;
pq.emplace(edgeWeight, adjNode);
}
}
}
fout << total_cost << '\n';
vector<pair<int, int>> mst_edges;
for (int i = 1; i <= n; ++i)
{
if (parent[i] != -1)
mst_edges.emplace_back(parent[i], i);
}
fout << mst_edges.size() << '\n';
for (const auto& edge : mst_edges)
{
fout << edge.first << ' ' << edge.second << '\n';
}
}
int main()
{
int n, m;
fin >> n >> m;
vector<vector<pair<int, int>>> graph(n + 1);
for (int i = 0; i < m; i++)
{
int a, b, c;
fin >> a >> b >> c;
graph[a].emplace_back(b, c);
graph[b].emplace_back(a, c);
}
primsAlgorithm(graph, n);
return 0;
}