Pagini recente » Cod sursa (job #527612) | Cod sursa (job #2068589) | Cod sursa (job #2336596) | Cod sursa (job #1436615) | Cod sursa (job #1755250)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <list>
using namespace std;
const int _ = 0;
const int oo = 0x3f3f3f3f;
const int s = 0;
int main() {
#ifdef INFOARENA
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
#endif
cin.sync_with_stdio(false);
int n, m;
cin >> n >> m;
vector<vector<pair<int,int>>> al(n);
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
u--, v--;
al[u].emplace_back(w, v);
}
vector<int> dist(n, oo);
dist[s] = 0;
queue<int> q;
q.push(s);
vector<bool> inQ(n, false);
inQ[s] = true;
vector<bool> rlx(n, false);
rlx[s] = true;
list<pair<int,int>> t {{0, s}, {0, _}};
vector<list<pair<int,int>>::iterator> pos(n, t.end());
pos[s] = t.begin();
// int nrelax = 0;
while (!q.empty()) {
auto u = q.front();
q.pop();
inQ[u] = false;
if (!rlx[u]) continue;
rlx[u] = false;
for (auto e: al[u]) {
int w = e.first;
int v = e.second;
if (dist[v] > dist[u]+w) {
int dif = dist[u]+w-dist[v];
dist[v] = dist[u]+w;
if (pos[v] != t.end()) {
int lvl = pos[v]->first;
auto it = t.erase(pos[v]);
while (it->first > lvl) {
int x = it->second;
if (x == u) {
puts("Ciclu negativ!");
return 0;
}
rlx[x] = false;
dist[x] += dif+1;
pos[x] = t.end();
it = t.erase(it);
}
}
pos[v] = t.emplace(next(pos[u]), pos[u]->first+1, v);
rlx[v] = true;
if (!inQ[v]) {
q.push(v);
inQ[v] = true;
}
}
// nrelax++;
}
}
for (int i = 1; i < n; i++) {
printf("%d%c", dist[i], " \n"[i == n-1]);
}
// printf("%d\n", nrelax);
}