Pagini recente » Cod sursa (job #2675124) | Cod sursa (job #2204914) | Cod sursa (job #500798) | Cod sursa (job #967724) | Cod sursa (job #1755171)
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#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;
list<int> q;
q.push_back(S);
vector<list<int>::iterator> posQ(n, q.end());
posQ[S] = q.begin();
list<pair<int,int>> t {{0, S}, {0, 0}};
vector<list<pair<int,int>>::iterator> posT(n, t.end());
posT[S] = t.begin();
// int nrelax = 0;
do {
auto u = q.front();
q.pop_front();
posQ[u] = q.end();
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 (posT[v] != t.end()) {
int lvl = posT[v]->first;
auto it = t.erase(posT[v]);
while (it->first > lvl) {
int x = it->second;
if (x == u) {
puts("Ciclu negativ!");
return 0;
}
if (posQ[x] != q.end()) {
q.erase(posQ[x]);
posQ[x] = q.end();
}
dist[x] += dif+1;
posT[x] = t.end();
it = t.erase(it);
}
}
posT[v] = t.emplace(next(posT[u]), posT[u]->first+1, v);
if (posQ[v] == q.end()) {
q.push_back(v);
posQ[v] = prev(q.end());
}
// nrelax++;
}
}
} while (!q.empty());
// printf("%d\n", nrelax);
for (int i = 1; i < n; i++) {
printf("%d%c", dist[i], " \n"[i == n-1]);
}
}