Pagini recente » Cod sursa (job #2630980) | Cod sursa (job #2189671) | Cod sursa (job #487478) | Cod sursa (job #2205883) | Cod sursa (job #3165056)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int NMAX = 50003, INF = 1e8;
vector<pair<int, int> > g[NMAX]; // nod, cost
int d[NMAX], n;
struct dcmp {
bool operator()(const pair<int, int> &a, const pair<int, int> &b) {
return a.second < b.second;
}
};
void dijkstra(int s) {
for (int i = 1; i <= n; i++)
d[i] = INF;
d[s] = 0;
priority_queue<pair<int, int>, vector<pair<int, int> >, dcmp> pq;
for (auto nxt : g[s]) {
pq.push(nxt);
}
while (!pq.empty()) {
int nod = pq.top().first, cost = pq.top().second;
pq.pop();
if (cost > d[nod])
return;
d[nod] = cost;
for (auto nxt : g[nod]) {
if (cost + nxt.second < d[nxt.first]) {
d[nxt.first] = cost + nxt.second;
pq.push(make_pair(nxt.first, cost + nxt.second));
}
}
}
}
int main() {
int m;
fin >> n >> m;
while (m--) {
int x, y, c;
fin >> x >> y >> c;
g[x].push_back(make_pair(y, c));
}
dijkstra(1);
for (int i = 1; i <= n; i++)
fout << d[i] << ' ';
return 0;
}