Pagini recente » Cod sursa (job #3315390) | Monitorul de evaluare | Monitorul de evaluare | Cod sursa (job #3309311) | Cod sursa (job #3357823)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
vector<vector<pair<int, int>>> gr(50100);
vector<long long> dist(50100, INT_MAX);
vector<int> cnt(50100, 0);
vector<bool> inQueue(50100, false);
queue<int> Q;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, val;
cin >> a >> b >> val;
gr[a].push_back({b, val});
}
dist[1] = 0;
Q.push(1);
inQueue[1] = true;
while (!Q.empty()) {
int node = Q.front();
Q.pop();
inQueue[node] = false;
for (auto &edge : gr[node]) {
int neighbor = edge.first;
int weight = edge.second;
if (dist[node] + weight < dist[neighbor]) {
dist[neighbor] = dist[node] + weight;
cnt[neighbor] = cnt[node] + 1;
if (cnt[neighbor] >= n) {
cout << "Ciclu negativ!";
return 0;
}
if (!inQueue[neighbor]) {
Q.push(neighbor);
inQueue[neighbor] = true;
}
}
}
}
for (int i = 2; i <= n; i++) {
cout << dist[i] << " ";
}
return 0;
}