Pagini recente » Monitorul de evaluare | Cod sursa (job #694342) | Cod sursa (job #3333561) | Cod sursa (job #485348) | Cod sursa (job #3333772)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
const int nmax = 50005;
const int inf = INT_MAX;
struct muchie {
int y, c;
};
vector<muchie> adj[nmax];
int dist[nmax];
int nr[nmax];
bool in_queue[nmax];
int n, m;
bool bellman_ford(int start_node) {
queue<int> q;
for (int i = 1; i <= n; i++) {
dist[i] = inf;
in_queue[i] = false;
nr[i] = 0;
}
dist[start_node] = 0;
q.push(start_node);
in_queue[start_node] = true;
while (!q.empty()) {
int x = q.front();
q.pop();
in_queue[x] = false;
for (auto it : adj[x]) {
int y = it.y;
int c = it.c;
if (dist[y] > dist[x] + c) {
dist[y] = dist[x] + c;
if (!in_queue[y]) {
q.push(y);
in_queue[y] = true;
nr[y]++;
if (nr[y] >= n) {
return false;
}
}
}
}
}
return true;
}
int main() {
f >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y, c;
f >> x >> y >> c;
adj[x].push_back({y, c});
}
if (!bellman_ford(1)) {
g << "Ciclu negativ!";
} else {
for (int i = 2; i <= n; i++) {
g << dist[i] << " ";
}
}
return 0;
}