Pagini recente » Cod sursa (job #627279) | Cod sursa (job #1694924) | Cod sursa (job #1274027) | Cod sursa (job #2359819) | Cod sursa (job #3300790)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 5e4 + 5;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct Edge {
int dest, cost;
};
int n, m;
vector<Edge> graph[MAXN];
int relaxCount[MAXN];
int distances[MAXN];
bool inQueue[MAXN];
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() {
fill(distances, distances + n + 1, INF);
memset(relaxCount, 0, sizeof(relaxCount));
memset(inQueue, 0, sizeof(inQueue));
queue<int> q;
distances[1] = 0;
q.push(1);
inQueue[1] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
inQueue[u] = false;
for (Edge e : graph[u]) {
if (distances[e.dest] > distances[u] + e.cost) {
distances[e.dest] = distances[u] + e.cost;
if (!inQueue[e.dest]) {
q.push(e.dest);
inQueue[e.dest] = true;
relaxCount[e.dest]++;
if (relaxCount[e.dest] > n)
return false; // Negative cycle
}
}
}
}
return true;
}
void Solve() {
if (!BellmanFord()) {
fout << "Ciclu!\n";
return;
}
for (int i = 2; i <= n; ++i) {
fout << distances[i] << ' ';
}
fout << '\n';
}
int main() {
ReadData();
Solve();
return 0;
}