Pagini recente » Cod sursa (job #718211) | Cod sursa (job #783134) | Cod sursa (job #1225913) | Cod sursa (job #2502508) | Cod sursa (job #3136767)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
int noduri, muchii;
vector<pair<int,int>> graf[500000],apm;
int vizitat[500000];
int costTotal;
ifstream f("apm.in");
ofstream g("apm.out");
priority_queue<pair<int,pair<int,int> > > coada;
//coada cu cost si muchii
int parinte[500000];
int distanta[500000];
void citire()
{
f>>noduri>>muchii;
for(int i=0;i<muchii;i++)
{
int x,y,c;
f>>x>>y>>c;
graf[x].push_back({y,c});
graf[y].push_back({x,c});
}
}
void Prim()
{
//nodul de start este 1, cu tatal 0 si cost 0
coada.push({0,{1,0}});
while(!coada.empty())
{
int cost = coada.top().first;
int nodCurent = coada.top().second.first;
int nodParinte = coada.top().second.second;
coada.pop();
if(vizitat[nodCurent] != 0)
continue;
costTotal -= cost;
if(nodParinte)
apm.push_back({nodParinte,nodCurent});
if(vizitat[nodCurent] == 0)
{
// bag toate muchiile
for(auto pereche: graf[nodCurent])
{
int vecin = pereche.first;
int cost = pereche.second;
if(vizitat[vecin] == 0)
coada.push({-cost,{vecin,nodCurent}});
}
vizitat[nodCurent] = 1;
}
}
}
int main()
{
citire();
Prim();
g<<costTotal;
for(auto pereche: apm)
{
g<<pereche.first<<" "<<pereche.second<<"\n";
}
return 0;
}