Pagini recente » Cod sursa (job #3348528) | Borderou de evaluare (job #1000525) | Cod sursa (job #3344537) | Cod sursa (job #3337140) | Cod sursa (job #3327360)
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
fstream cinn("bellmanford.in");
fstream coutt("bellmanford.out");
int n,m;
vector<pair<int,pair<int,int>>> muchii;
vector<int> dist;
const int INF = 1e9;
void bellman_ford(int n, int m, int start) {
dist.assign(n + 1, INF);
dist[start] = 0;
for ( int i = 1; i<n; i++ ) {
for ( auto edge : muchii ) {
int x = edge.first;
int y = edge.second.first;
int w = edge.second.second;
if ( dist[y] > dist[x] + w ) {
dist[y] = dist[x] + w;
}
}
}
bool negative_cycle = false;
for ( auto edge : muchii ) {
int x = edge.first;
int y = edge.second.first;
int w = edge.second.second;
if ( dist[y] > dist[x] + w ) {
dist[y] = dist[x] + w;
negative_cycle = true;
}
}
if ( negative_cycle ) {
coutt << "Ciclu negativ!\n";
} else {
for ( int i = 1; i<=n; i++ ) {
coutt << dist[i] << " ";
}
}
}
int main() {
cin >> n >> m;
for ( int i = 0; i<m; i++ ) {
int x, y, w;
cinn >> x >> y >> w;
muchii.push_back({x, {y, w}});
}
bellman_ford(n, m, 1);
return 0;
}