Pagini recente » Cod sursa (job #866816) | Cod sursa (job #3277923) | Cod sursa (job #2043237) | Cod sursa (job #382729) | Cod sursa (job #2844225)
#include <iostream>
#include <queue>
#include <vector>
#include <utility>
#include <fstream>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
priority_queue<pair<int, int>> elements;
vector<vector<int> > neighbours(50001);
vector<int> dist(50001, -1);
void dijkstra(int node, int sum) {
for (int i = 0; i < neighbours[node].size(); i += 2) {
if (dist[neighbours[node][i]] == -1) {
dist[neighbours[node][i]] = neighbours[node][i + 1] + sum;
elements.push({dist[neighbours[node][i]] * -1, neighbours[node][i]});
} else if (dist[neighbours[node][i]] > neighbours[node][i + 1] + sum) {
dist[neighbours[node][i]] = neighbours[node][i + 1] + sum;
elements.push({dist[neighbours[node][i]] * -1, neighbours[node][i]});
}
}
}
int main() {
int n, m;
fin >> n >> m;
for (int i = 1, x, y, z; i <= m; ++i) {
fin >> x >> y >> z;
neighbours[x].push_back(y);
neighbours[x].push_back(z);
}
elements.push({0, 1});
dist[1] = 0;
while (!elements.empty()) {
dijkstra(elements.top().second, dist[elements.top().second]);
elements.pop();
}
for (int i = 2; i <= n; ++i) {
if (dist[i] == -1) {
fout << "0 ";
} else {
fout << dist[i] << ' ';
}
}
}