Pagini recente » Cod sursa (job #277942) | Cod sursa (job #1571047) | Cod sursa (job #2664138) | Cod sursa (job #1735613) | Cod sursa (job #2536314)
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
#define INF 0x7f7f7f7f
int n, m;
vector<pair<int, int> > nod[50010];
priority_queue < pair<int, int> > heap;
int dist[50010];
void readAndSet() {
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int a, b, cost;
fin >> a >> b >> cost;
nod[a].push_back(make_pair(b, cost));
}
}
void dijkstra() {
memset(dist, INF, sizeof dist);
heap.push(make_pair(0, 1));
dist[1] = 0;
while (!heap.empty()) {
int actCost = -heap.top().first;
int from = heap.top().second;
heap.pop();
if(actCost != dist[from])
continue;
for (pair<int, int> way : nod[from]) {
int to = way.first;
int newCost = actCost + way.second;
if (newCost < dist[to]) {
heap.push(make_pair(-newCost, to));
dist[to] = newCost;
}
}
}
}
void printDist() {
for (int i = 2; i <= n; i++)
if (dist[i] == INF)
fout << 0 << ' ';
else
fout << dist[i] << ' ';
}
int main() {
readAndSet();
dijkstra();
printDist();
return 0;
}