Pagini recente » Cod sursa (job #874226) | Cod sursa (job #2153270) | Cod sursa (job #2183646) | Cod sursa (job #2883997) | Cod sursa (job #2964731)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, x, y, z;
vector<pair<int, int>> g[50001];
vector<int> dist(50001, INT_MAX), nr(50001);
queue<int> q;
bool viz[50001];
bool bellmanford() {
q.push(1);
dist[1] = 0;
while (!q.empty()) {
int t = q.front();
q.pop();
viz[t] = 0;
for (auto& x : g[t]) {
if (dist[x.first] > dist[t] + x.second) {
nr[x.first]++;
if (nr[x.first] > n) {
return 0;
}
dist[x.first] = dist[t] + x.second;
if (!viz[x.first]) {
q.push(x.first);
}
viz[x.first] = 1;
}
}
}
return 1;
}
int main() {
fin >> n >> m;
for (int i = 0; i < m; i++) {
fin >> x >> y >> z;
g[x].push_back(make_pair(y, z));
}
if (bellmanford()) {
for (int i = 2; i <= n; i++) {
fout << dist[i] << " ";
}
} else {
fout << "Ciclu negativ!";
}
}