Pagini recente » Cod sursa (job #3268634) | Cod sursa (job #1435474) | Cod sursa (job #1190108) | Cod sursa (job #2052083) | Cod sursa (job #2173783)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
struct Node { int x, cost; };
class Cmp {
public:
bool operator()(Node a, Node b) {
return a.cost > b.cost;
}
};
const int INF = 2e9;
const int MAXN = 50005;
int n, m;
int dist[MAXN];
bool viz[MAXN];
vector<Node> g[MAXN];
priority_queue<Node, vector<Node>, Cmp> q;
void Dijkstra() {
for (int i = 1; i <= n; ++i) dist[i] = INF;
dist[1] = 0;
q.push({1, 0});
while (!q.empty()) {
Node now = q.top(); q.pop();
int x = now.x;
if (viz[x]) continue;
viz[x] = true;
dist[x] = now.cost;
for (Node &e : g[x]) {
int y = e.x;
if (viz[y]) continue;
if (dist[x] + e.cost < dist[y]) {
dist[y] = dist[x] + e.cost;
q.push({y, dist[y]});
}
}
}
}
int main()
{
in >> n >> m;
for (int i = 1, x, y, cost; i <= m; ++i) {
in >> x >> y >> cost;
g[x].push_back({y, cost});
}
Dijkstra();
for (int i = 2; i <= n; ++i)
if (dist[i] == INF) out << 0 << " ";
else out << dist[i] << " ";
return 0;
}