Pagini recente » Cod sursa (job #3286636) | Cod sursa (job #2911280) | Cod sursa (job #3036613) | Cod sursa (job #1169) | Cod sursa (job #3287330)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int prim(vector<vector<pair<int, int>>> &adj, int n, vector<pair<int, int>> &mst_edges)
{
priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> pq;
vector<bool> visited(n+1, false);
int res = 0;
pq.push({0, {-1, 1}});
while(!pq.empty()){
int currNode = pq.top().second.second;
int lastNode = pq.top().second.first;
int cost = pq.top().first;
pq.pop();
if(visited[currNode]){
continue;
}
visited[currNode] = true;
mst_edges.push_back({lastNode, currNode});
res += cost;
for(int i = 0; i < adj[currNode].size(); i++){
int newNode = adj[currNode][i].first;
int add_cost = adj[currNode][i].second;
if(!visited[newNode]){
pq.push({add_cost, {currNode, newNode}});
}
}
}
return res;
}
int main()
{
int n, m;
fin >> n >> m;
vector<vector<pair<int, int>>> adj(n+2);
for(int i = 0; i < m; i++){
int a, b, c;
fin >> a >> b >> c;
adj[a].push_back({b, c});
adj[b].push_back({a, c});
}
vector<pair<int, int>> mst_edges;
fout << prim(adj, n, mst_edges) << endl;
fout << n-1 << endl;
for(int i = 1; i < mst_edges.size(); i++){
fout << mst_edges[i].first << " " << mst_edges[i].second << endl;
}
return 0;
}