Pagini recente » Cod sursa (job #1698797) | Cod sursa (job #2990224) | Statisticile problemei Album2 | Cod sursa (job #3281229) | Cod sursa (job #3300570)
#include <bits/stdc++.h>
using namespace std;
int main() {
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
fin >> n >> m;
vector<vector<pair<int, int>>> adj(n+1);
for (int i = 0, x, y, c; i < m; ++i) {
fin >> x >> y >> c;
adj[x].push_back(make_pair(y, c));
}
vector<int> d(n + 1, INT_MAX), cnt(n + 1, 0);
d[1] = 0;
queue<int> q;
q.push(1);
while (!q.empty()) {
int nod = q.front(); q.pop();
for (auto& [vec, cost] : adj[nod]) {
if (d[vec] > d[nod] + cost) {
d[vec] = d[nod] + cost;
q.push(vec);
++cnt[vec];
if (cnt[vec] >= n) {
fout << "Ciclu negativ!\n";
return 0;
}
}
}
}
for (int i = 2; i <= n; ++i)
fout << d[i] << ' ';
fout << '\n';
return 0;
}