Pagini recente » Cod sursa (job #2381569) | Cod sursa (job #839936) | Cod sursa (job #3152068) | Cod sursa (job #1632674) | Cod sursa (job #1755148)
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <queue>
#include <list>
using namespace std;
const int oo = 0x3f3f3f3f;
const int S = 0;
int main() {
ios::sync_with_stdio(false);
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
int n, m;
cin >> n >> m;
vector<vector<pair<int,int>>> adjl(n);
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
u--, v--;
adjl[u].emplace_back(w, v);
}
vector<int> dist(n, oo);
dist[S] = 0;
queue<int> q;
q.push(S);
vector<bool> inq(n);
inq[S] = true;
list<pair<int,int>> lst {{0, S}, {0, 0}};
vector<list<pair<int,int>>::iterator> pos(n, lst.end());
pos[S] = lst.begin();
// int nrelax = 0;
do {
auto u = q.front();
q.pop();
if (!inq[u]) continue;
inq[u] = false;
for (auto e: adjl[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] != lst.end()) {
int lvl = pos[v]->first;
auto it = lst.erase(pos[v]);
while (it->first > lvl) {
int x = it->second;
if (x == u) {
puts("Ciclu negativ!");
return 0;
}
dist[x] += dif + !inq[x];
pos[x] = lst.end();
it = lst.erase(it);
}
}
pos[v] = lst.emplace(next(pos[u]), pos[u]->first+1, v);
if (!inq[v]) {
q.push(v);
inq[v] = true;
}
// nrelax++;
}
}
} while (!q.empty());
// printf("%d\n", nrelax);
for (int i = 1; i < n; i++) {
printf("%d%c", dist[i], " \n"[i == n-1]);
}
}