Pagini recente » Cod sursa (job #1244585) | Cod sursa (job #185660) | Cod sursa (job #1060069) | Cod sursa (job #1523525) | Cod sursa (job #2858844)
#include <algorithm>
#include <iostream>
#include <cstring>
#include <fstream>
#include <cassert>
#include <vector>
#include <set>
using namespace std;
const int NMAX = 50005;
const int MAX_SUM = 1000001;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
vector<pair<int, int>> graph[NMAX];
int dist[NMAX];
int main() {
int n, m;
fin >> n >> m;
for (int i = 0; i < m; ++i) {
int start, end, cost;
fin >> start >> end >> cost;
graph[start].push_back(make_pair(end, cost));
}
memset(dist, MAX_SUM, sizeof dist);
dist[1] = 0;
set<pair<int, int>> positions;
positions.insert(make_pair(0, 1));
while (!positions.empty()) {
int node = positions.begin()->second;
positions.erase(positions.begin());
for (pair<int, int> next : graph[node]) {
int to = next.first;
int cost = next.second;
if (dist[to] > dist[node] + cost) {
if (dist[to] != MAX_SUM) {
positions.erase(positions.find(make_pair(dist[to], to)));
}
dist[to] = dist[node] + cost;
positions.insert(make_pair(dist[to], to));
}
}
}
for (int i = 2; i <= n; ++i) {
if (dist[i] == MAX_SUM) {
dist[i] = 0;
}
fout << dist[i] << ' ';
}
}