Pagini recente » Cod sursa (job #252699) | Cod sursa (job #11981) | Cod sursa (job #65201) | Cod sursa (job #3218250) | Cod sursa (job #2887758)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct Edge {
int b, v;
};
struct Node {
int a, v;
};
bool operator<(const Node &lhs, const Node &rhs) {
return lhs.v > rhs.v || (lhs.v == rhs.v && lhs.a < rhs.a);
}
const int INF = 0x3f3f3f3f;
const int N = 50041;
const int M = 250041;
int n, m;
vector<Edge> gra[N];
int d[N], c[N];
bool inq[N];
int main() {
fin >> n >> m;
for (int i = 0; i < m; ++i) {
int a, b, v;
fin >> a >> b >> v;
gra[a].push_back({b, v});
}
for (int i = 1; i <= n; ++i) {
d[i] = INF;
}
bool negative_cycle = false;
priority_queue<Node> pq;
d[1] = 0;
pq.push({1, 0});
inq[1] = true;
while (!negative_cycle && !pq.empty()) {
auto node = pq.top(); pq.pop();
inq[node.a] = false;
for (auto edge : gra[node.a]) {
if (node.v + edge.v < d[edge.b]) {
d[edge.b] = node.v + edge.v;
if (!inq[edge.b]) {
pq.push({edge.b, node.v + edge.v});
inq[edge.b] = true;
}
c[edge.b]++;
if (c[edge.b] >= n) { negative_cycle = true; }
}
}
}
if (negative_cycle) {
fout << "Ciclu negativ!";
} else {
for (int i = 2; i <= n; ++i) {
fout << d[i] << " ";
}
}
return 0;
}