Pagini recente » Cod sursa (job #609495) | Cod sursa (job #2452203) | Cod sursa (job #798557) | Cod sursa (job #1862366) | Cod sursa (job #3262313)
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<pair<int, int>> v[50001];
int cost[50001], vis[50001];
struct nod {
int node, cost;
bool operator < (const nod& a) const {
return cost > a.cost;
}
};
bool bellman(int start) {
memset(cost, 0x3f, sizeof(cost));
priority_queue<nod> q;
q.push({start, 0});
cost[start] = 0;
while (!q.empty()) {
int node = q.top().node;
q.pop();
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;
++vis[v[node][i].first];
q.push({v[node][i].first, cost[v[node][i].first]});
}
}
}
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!";
}
}