Pagini recente » Cod sursa (job #375079) | Cod sursa (job #3345685) | Cod sursa (job #2801237) | Cod sursa (job #1362943) | Cod sursa (job #3336355)
#include <iostream>
#include <vector>
#include <algorithm>
#define pii pair<int, int>
using namespace std;
const int NMAX = 5 * 1e5 + 5;
const char nl = '\n';
const int INF = 1e9 + 7;
struct edge {
int u, v, weight;
};
vector<pii> graph[NMAX];
vector<edge> edges;
int dist[NMAX];
void bellmanford(int source, int n) {
for(int i = 1; i <= n; ++i) {
dist[i] = INF;
}
dist[source] = 0;
for(int i = 1; i < n; ++i) {
for(auto edg: edges) {
if(dist[edg.u] == INF) {
continue;
}
if(dist[edg.v] > dist[edg.u] + edg.weight) {
dist[edg.v] = dist[edg.u] + edg.weight;
}
}
}
bool cycle = false;
for(auto edg: edges) {
if(dist[edg.v] > dist[edg.u] + edg.weight) {
cycle = true;
break;
}
}
if(cycle) {
cout << "Ciclu negativ!" << nl;
} else {
for(int i = 2; i <= n; ++i) {
cout << dist[i] << ' ';
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
int n, m;
cin >> n >> m;
for(int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back({v, w});
edges.push_back({u, v, w});
}
bellmanford(1, n);
return 0;
}