Pagini recente » Cod sursa (job #729978) | Cod sursa (job #2320732) | Cod sursa (job #847970) | Cod sursa (job #1224942) | Cod sursa (job #2922133)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <climits>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
const int NMAX=200001;
vector <pair<int,int>> graf[NMAX];
int d[NMAX];
int parent[NMAX];
bool visited[NMAX];
priority_queue<pair<int,int>>h;
int main()
{
int n,m;
in>>n>>m;
int x,y,cost;
for(int i=1; i<=m; i++)
{
in>>x>>y>>cost;
graf[x].push_back(make_pair(y,cost));
graf[y].push_back(make_pair(x,cost));
}
for(int i=1; i<=n; i++)
{
d[i]=INT_MAX;
parent[i]=-1;
}
//pereche cost-nod
h.push(make_pair(0,1));
d[1]=0;
while(h.empty()==0)
{
while(h.empty()==0 && visited[h.top().second]==1)
{
h.pop();
}
if(h.empty()==1)
{
break;
}
x=h.top().second;
visited[x]=1;
for(unsigned int i=0; i<graf[x].size(); i++)
{
y=graf[x][i].first;
cost=graf[x][i].second;
if(d[y]>cost && visited[y]==0)
{
d[y]=cost;
h.push(make_pair(-d[y],y));
parent[y]=x;
}
}
}
int cost_min=0;
for(int i=1; i<=n; i++)
{
if(parent[i]!=-1)
cost_min+=d[i];
}
out<<cost_min<<"\n";
out<<n-1<<'\n';
for(int i=1; i<=n; i++)
{
if(parent[i]!=-1)
out<<i<<" "<<parent[i]<<'\n';
}
return 0;
}