Pagini recente » Cod sursa (job #470963) | Cod sursa (job #407226) | Cod sursa (job #2832694) | Cod sursa (job #664756) | Cod sursa (job #2699736)
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <set>
using namespace std;
int n,p,from,to,cost,i,dist[50005],nod;
const int INF=0x3f3f3f3f;
vector < pair < int, int> > G[50005];
set < pair < int, int > > h;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int main()
{
in>>n>>p;
while (in>>from>>to>>cost)
{
G[from].push_back(make_pair(to, cost));
}
memset(dist,INF, sizeof dist);
dist[p]=0;
h.insert(make_pair(0,p));
while (!h.empty())
{
nod=h.begin()->second;
h.erase(h.begin());
for (vector < pair< int, int > > ::iterator it=G[nod].begin(); it!=G[nod].end(); it++)
{
int to=it->first;
int cost=it->second;
if (dist[to]>dist[nod]+cost)
{
if (dist[to]!=INF)
h.erase(h.find(make_pair(dist[to],to)));
dist[to]=dist[nod]+cost;
h.insert(make_pair(dist[to],to));
}
}
}
for (i=1; i<=n; i++)
{
if (dist[i]==INF)
dist[i]=-1;
out<<dist[i]<<" ";
}
}