Pagini recente » Cod sursa (job #1866420) | Cod sursa (job #2084174) | Cod sursa (job #2875836) | Cod sursa (job #212521) | Cod sursa (job #2203570)
// https://goo.gl/fBmFxu
#include <bits/stdc++.h>
using namespace std;
#define NMAX 100009
#define MMAX 200009
#define kInf (1 << 30)
#define kInfLL (1LL << 60)
#define kMod 666013
#define edge pair<int, int>
#define x first
#define c second
#define USE_FILES "MLC"
#ifdef USE_FILES
#define cin fin
#define cout fout
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
#endif
// number of tests from "in"
int test_cnt = 1;
void clean_test();
// your global variables are here
// your solution is here
vector<edge>G[NMAX];
int n, m, start;
vector<int> d;
bool BellmanFord(int start, vector<int>&d) {
for (int i = 1; i <= n; ++i) {
d[i] = kInf;
}
queue<int>q;
vector<int>qcnt(n + 1, 0);
q.push(start);
d[start] = 0;
while (!q.empty()) {
int node = q.front();
q.pop();
for (auto &p : G[node]) {
int x = p.x, c = p.c;
if (d[node] + c < d[x]) {
d[x] = d[node] + c;
q.push(x);
++qcnt[x];
if (qcnt[x] == n) return false;
}
}
}
for (int i = 1; i <= n; ++i) {
if (d[i] == kInf) {
d[i] = 0;
}
}
return true;
}
void solve() {
cin >> n >> m;
for (int i = 1; i <= m; ++i) {
int x, y, cost;
cin >> x >> y >> cost;
G[x].push_back({y, cost});
}
d.resize(n + 1);
bool e_ok = BellmanFord(1, d);
if (e_ok) {
for (int i = 2; i <= n; ++i) {
cout << d[i] << " ";
}
} else {
cout << "Ciclu negativ!\n";
}
if (test_cnt > 0) {
clean_test();
}
}
void clean_test() {
// clean if needed
for (int i = 1; i <= n; ++i) {
G[i].clear();
}
d.clear();
}
int main() {
//cin >> test_cnt;
while (test_cnt--) {
solve();
}
return 0;
}