Pagini recente » Cod sursa (job #935976) | Cod sursa (job #85506) | Cod sursa (job #85509) | Cod sursa (job #735968) | Cod sursa (job #3300792)
#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
#include <fstream>
#include <cstring>
using namespace std;
#define fast_io ios::sync_with_stdio(0); cin.tie(0); do{}while(0)
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 5e4 + 5;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct Edge {
int dest, c;
};
int n, m;
vector<Edge> graph[MAXN];
int realax[MAXN];
int distances[MAXN];
bool inQueue[MAXN];
queue<Edge> q;
void ReadData() {
fin >> n >> m;
int a, b, c;
for (int i = 0; i < m; i++) {
fin >> a >> b >> c;
graph[a].push_back({b, c});
}
}
bool BellmanFord() {
memset(distances, INF, sizeof(distances));
distances[1] = 0;
inQueue[1] = true;
q.push({1, 0});
while (!q.empty()) {
Edge curr = q.front();
inQueue[curr.dest] = false;
q.pop();
for (Edge e : graph[curr.dest]) {
if (distances[e.dest] <= distances[curr.dest] + e.c) {
continue;
}
distances[e.dest] = distances[curr.dest] + e.c;
if (!inQueue[e.dest]) {
q.push({e.dest, distances[e.dest]});
inQueue[e.dest] = true;
realax[e.dest]++;
if (realax[e.dest] > n) {
return false;
}
}
}
}
return true;
}
void Solve() {
if (!BellmanFord()) {
fout << "Ciclu negativ!\n";
return;
}
for (int i = 2; i <= n; i++) {
fout << distances[i] << ' ';
}
fout << '\n';
}
int main() {
ReadData();
Solve();
return 0;
}