Pagini recente » Cod sursa (job #2874168) | Cod sursa (job #558330) | Cod sursa (job #1502035) | Cod sursa (job #1264154) | Cod sursa (job #3323276)
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m;
vector<vector<pair<int, int>>> adj;
void Prim(int s, vector<pair<int, int>> &apcm, int&cost){
set<pair<int, int>> q;
vector<int> d(n+1, 1e9), tata(n+1, 0), viz(n+1, 0);
d[s] = 0;
q.insert({d[s], s});
while(!q.empty()){
auto z=q.begin();
pair<int,int> p=*z;
q.erase(z);
if (viz[p.second]==1) continue; //ignoram nodurile care au mai fost deja vizitate, acum sunt extrase copii ale lor cu etichete mai mari
viz[p.second] = 1;
for(auto &nod : adj[p.second]){
int vf = nod.first;
int cost = nod.second;
if(d[vf] > cost && !viz[vf]){
tata[vf] = p.second;
q.erase({d[vf], vf}); //sterg perechea daca exista
d[vf] = cost;
q.insert({d[vf], vf});
}
}
}
for(int i=1; i<=n; ++i){
if(tata[i] != 0){
apcm.push_back({i, tata[i]});
cost += d[i];
}
}
}
int main(){
fin>>n>>m;
adj.resize(n+1);
while(m--){
int x, y, cost;
fin>>x>>y>>cost;
adj[x].push_back({y, cost});
adj[y].push_back({x, cost});
}
vector<pair<int, int>> apcm;
int cost = 0;
Prim(1,apcm,cost);
fout<<cost<<'\n';
fout<<apcm.size()<<'\n';
for(auto &e : apcm){
fout<<e.first<<" "<<e.second<<'\n';
}
fout.close();
return 0;
}