Pagini recente » Cod sursa (job #3354897) | Cod sursa (job #3349907) | Cod sursa (job #3322784) | Cod sursa (job #3328045) | Cod sursa (job #3327367)
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
ifstream cinn("bellmanford.in");
ofstream 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 = 2; i<=n; i++ ) {
coutt << dist[i] << " ";
}
}
}
int main() {
cinn >> 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;
}