Pagini recente » Cod sursa (job #2608771) | Cod sursa (job #564421) | Cod sursa (job #1081211) | Cod sursa (job #2690421) | Cod sursa (job #2716945)
#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;
}
};
const int oo = 2e9;
int n, m;
vector <vector <pair <int, int> > > v;
vector <int> d;
priority_queue <edge> q;
void init() {
v = vector <vector <pair <int, int> > > (n + 1);
d = vector <int> (n + 1, oo);
}
void read() {
f >> n >> m;
init();
int x, y, cost;
for(int i = 1; i <= m; ++i) {
f >> x >> y >> cost;
v[x].push_back({y, cost});
}
}
void dijkstra() {
d[1] = 0;
q.push({1, 0});
int node, otherNode, dist, otherDist;
while(!q.empty()) {
edge Edge = q.top();
q.pop();
node = Edge.node;
dist = Edge.dist;
if(dist > d[node])
continue;
for(const auto& p : v[node]) {
otherNode = p.first;
otherDist = p.second;
if(dist + otherDist < d[otherNode]) {
d[otherNode] = dist + otherDist;
q.push({otherNode, d[otherNode]});
}
}
}
}
int main()
{
read();
dijkstra();
for(int i = 2; i <= n; ++i)
if(d[i] == oo)
g << 0 << " ";
else g << d[i] << " ";
return 0;
}