Pagini recente » Cod sursa (job #2297473) | Cod sursa (job #1344608) | Cod sursa (job #2128656) | Cod sursa (job #988545) | Cod sursa (job #2505619)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define pb push_back
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int MAXN = 50010;
const int INF = 0x3f3f3f3f;
struct Node {
int node, cost;
};
vector<Node> edges[MAXN];
queue<int> q;
int dist[MAXN], vis[MAXN], n, m;
void read() {
fin >> n >> m;
for (int i = 0; i < n; ++i) {
int x, y, c;
fin >> x >> y >> c;
edges[x].pb({y, c});
}
}
void initialize() {
for (int i = 1; i <= n; ++i)
dist[i] = INF;
}
bool bellmanford() {
dist[1] = 0;
q.push(1);
vis[1] = 1;
while (!q.empty()) {
int node = q.front();
q.pop();
for (const auto &it: edges[node])
if (dist[it.node] > dist[node] + it.cost) {
++vis[it.node];
if (vis[it.node] == n)
return false;
dist[it.node] = dist[node] + it.cost;
q.push(it.node);
}
}
return true;
}
void print() {
for (int i = 2; i <= n; ++i)
fout << dist[i] << ' ';
}
int main() {
read();
initialize();
if (bellmanford() == true)
print();
else
fout << "Ciclue negativ!";
return 0;
}