Pagini recente » Cod sursa (job #2150646) | Cod sursa (job #3161380) | Cod sursa (job #1061301) | Cod sursa (job #1163242) | Cod sursa (job #2920652)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMAX=50001;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
priority_queue < pair <int,int> > h;
vector <pair <int,int> >graph[NMAX];
bool visited[NMAX];
int dist[NMAX];
int main()
{
int n,m,x,y,cost;
in>>n>>m;
for(int i=1; i<=m; i++)
{
in>>x>>y>>cost;
graph[x].push_back(make_pair(y,cost));
}
//initializare
for(int i=1; i<=n; i++)
{
dist[i]=-1;
}
dist[1]=0;
h.push(make_pair(0,1));
while(h.empty()==false)
{
while(h.empty()==false && visited[h.top().second]==1)
{
h.pop();
}
if(h.empty()==true)
break;
x=h.top().second;
visited[x]=1;
for(unsigned int i=0; i<graph[x].size(); i++)
{
y=graph[x][i].first;
cost=graph[x][i].second;
if(dist[y]>dist[x]+cost || dist[y]==-1)
{
dist[y]=dist[x]+cost;
h.push(make_pair(-dist[y],y));
}
}
}
for(int i=2; i<=n; i++)
{
out<<dist[i]<<" ";
}
return 0;
}