Pagini recente » Cod sursa (job #2636260) | Cod sursa (job #1018054) | Cod sursa (job #599186) | Cod sursa (job #2511723) | Cod sursa (job #3278303)
#include <bits/stdc++.h>
using namespace std;
int main() {
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int INF = 1e9;
int n, m;
in >> n >> m;
vector<vector<pair<int, int>>> g(n + 1);
for(int i = 1; i <= m; i++) {
int x, y, c;
in >> x >> y >> c;
g[x].push_back({y, c});
}
vector<int> dist(n + 1, INF);
dist[1] = 0;
for(int t = 1; t < n; t++) {
for(int node = 1; node <= n; node++) {
for(auto [son, w] : g[node]) {
dist[son] = min(dist[son], dist[node] + w);
}
}
}
bool negativeCycle = false;
for(int node = 1; node <= n; node++) {
for(auto [son, w] : g[node]) {
if(dist[node] + w < dist[son]) {
negativeCycle = true;
break;
}
}
}
if(negativeCycle) {
out << "Ciclu negativ!";
} else {
for(int i = 2; i <= n; i++) {
out << dist[i] << ' ';
}
out << '\n';
}
return 0;
}