Pagini recente » Cod sursa (job #518124) | Cod sursa (job #2761867) | Cod sursa (job #2258325) | Cod sursa (job #1076847) | Cod sursa (job #3262325)
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<pair<int, int>> v[50001];
int cost[50001], vis[50001], inq[50001];
bool bellman(int start) {
memset(cost, 0x3f, sizeof(cost));
queue<int> q;
q.push(start);
cost[start] = 0;
while (!q.empty()) {
int node = q.front();
q.pop();
++vis[node];
if (vis[node] >= n) {
return false;
}
for (int i = 0; i < v[node].size(); ++i) {
if (cost[node] + v[node][i].second < cost[v[node][i].first]) {
cost[v[node][i].first] = cost[node] + v[node][i].second;
if (!inq[v[node][i].first]) {
inq[v[node][i].first] = 1;
q.push(v[node][i].first);
}
}
}
inq[node] = 0;
}
return true;
}
int main() {
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
cin >> n >> m;
for (int i = 1; i <= m; ++i) {
int x, y, c;
cin >> x >> y >> c;
v[x].push_back({y, c});
}
if (bellman(1)) {
for (int i = 2; i <= n; ++i) {
cout << cost[i] << " ";
}
} else {
cout << "Ciclu negativ!";
}
}