Pagini recente » Cod sursa (job #3137849) | Cod sursa (job #2500216) | Cod sursa (job #2710071) | Cod sursa (job #930033) | Cod sursa (job #2791029)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
struct edge {
int node, dist;
bool operator <(const edge& other) const {
return dist > other.dist;
}
};
using Graph = vector <vector<pair<int, int>>>;
Graph v;
vector <int> d;
priority_queue <edge> q;
int n, m;
const int oo = 2e9;
void init() {
v = Graph (n + 1);
d = vector <int> (n + 1, oo);
}
void read() {
f >> n >> m;
init();
int x, y, dist;
for(int i = 1; i <= m; ++i) {
f >> x >> y >> dist;
v[x].push_back({y, dist});
}
}
void dijkstra() {
q.push({1, 0});
d[1] = 0;
int node, other_node, dist, other_dist;
while(!q.empty()) {
node = q.top().node;
dist = q.top().dist;
q.pop();
if(dist > d[node])
continue;
for(const auto& p : v[node]) {
other_node = p.first;
other_dist = p.second;
if(dist + other_dist < d[other_node]) {
d[other_node] = dist + other_dist;
q.push({other_node, d[other_node]});
}
}
}
}
int main()
{
read();
dijkstra();
for(int i = 2; i <= n; ++i)
g << (d[i] != oo ? d[i] : 0) << " ";
}