Pagini recente » Cod sursa (job #1167851) | Cod sursa (job #580007) | Cod sursa (job #1993866) | Cod sursa (job #1162691) | Cod sursa (job #2280210)
#include <algorithm>
#include <fstream>
#include <cstring>
#include <cassert>
#include <vector>
#include <set>
using namespace std;
///INF = 0x3f3f3f3f;
vector < pair <int, int > > G[50005];
int dist[50005];
int main()
{
FILE *f=fopen("dijkstra.in","r");
FILE *g=fopen("dijkstra.out","w");
int n,m,i,from,to,cost;
fscanf (f,"%d%d",&n,&m);
assert(1 <= n && n <= 50000);
assert(1 <= m && m <= 250000);
for (i=0;i<m;i++)
{
fscanf (f,"%d%d%d",&from,&to,&cost);
assert(1 <= from && from <= n);
assert(1 <= to && to <= n);
assert(0 <= cost && cost <= 20000);
G[from].push_back(make_pair(to, cost));
}
memset(dist, INF, sizeof dist);
dist[1] = 0;
set< pair< int, int > > h;
h.insert(make_pair(0, 1));
while (!h.empty()) {
int node = h.begin()->second;
int d = h.begin()->first;
h.erase(h.begin());
for (vector < pair <int, int > > ::iterator it = G[node].begin(); it != G[node].end(); ++it) {
int to = it->first;
int cost = it->second;
if (dist[to] > dist[node] + cost) {
if (dist[to] != 0x3f3f3f3f) {
h.erase(h.find(make_pair(dist[to], to)));
}
dist[to] = dist[node] + cost;
h.insert(make_pair(dist[to], to));
}
}
}
for (i = 2; i <= n; ++i) {
if (dist[i] == INF) {
dist[i] = 0;
}
fprintf (g,"%d ",dist[i]);
}
fprintf (g,"\n");
}