Pagini recente » Cod sursa (job #2487622) | Cod sursa (job #1050860) | Cod sursa (job #1191328) | Cod sursa (job #1854522) | Cod sursa (job #2424425)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define NMAX 100000
#define INF 1e9
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int n, m;
priority_queue<pair<int, int > > pq;
int d[NMAX], vis[NMAX];
vector<int> a[NMAX], c[NMAX];
int main() {
f >> n >> m;
for (int i = 0; i < m; ++i) {
int x1, y1, cost1;
f >> x1 >> y1 >> cost1;
x1 --;
y1 --;
a[x1].push_back(y1);
c[x1].push_back(cost1);
}
for (int i = 0; i < n; ++i) {
d[i] = INF;
}
d[0] = 0;
pq.push({0, 0});
for (int i = 0; i < n && !pq.empty(); ++i) {
pair<int, int> pCurrent = pq.top();
pq.pop();
while(!pq.empty() && vis[pCurrent.first] == 1) {
pCurrent = pq.top();
pq.pop();
}
int nodCurent = pCurrent.second;
int costCurent = -pCurrent.first;
vis[nodCurent] = 1;
for (int j = 0; j < a[nodCurent].size(); ++j) {
int vecinCurent = a[nodCurent][j];
if (!vis[vecinCurent] && d[vecinCurent] > c[nodCurent][j] + costCurent) {
d[vecinCurent] = c[nodCurent][j] + costCurent;
pq.push(make_pair(-d[vecinCurent], vecinCurent));
}
}
}
for (int i = 1; i < n; ++i) {
if (d[i] == INF) {
g << "0 ";
} else {
g << d[i] << " ";
}
}
return 0;
}