Pagini recente » Cod sursa (job #2312694) | Cod sursa (job #1408787) | Cod sursa (job #532607) | Cod sursa (job #1518507) | Cod sursa (job #1398257)
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
#define fs first
#define sc second
#define pob pop_back
#define pub push_back
#define eps 1E-7
#define sz(a) a.size()
#define count_one __builtin_popcount;
#define count_onell __builtin_popcountll;
#define fastIO ios_base::sync_with_stdio(false)
#define PI (acos(-1.0))
#define linf (1LL<<62)//>4e18
#define inf (0x7f7f7f7f)//>2e9
#define MAXN 50010
#ifndef ONLINE_JUDGE
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
#endif
int n, m;
vector<pair<int, int> > vec[MAXN];
bitset<MAXN> viz;
queue<int> Q;
int dist[MAXN], cnt[MAXN];
bool negativeCycle;
void bford() {
for(int i = 2; i <= n; ++i)
dist[i] = inf;
int nod;
for(Q.push(1), viz[1] = true, negativeCycle = false; !Q.empty() && !negativeCycle; Q.pop()) {
nod = Q.front();
if(dist[nod] != inf)
for(auto it: vec[nod]) {
if(dist[it.fs] > dist[nod] + it.sc) {
dist[it.fs] = dist[nod] + it.sc;
if(!viz[it.fs])
if(cnt[it.fs] > n)
negativeCycle = true;
else
viz[it.fs] = true, Q.push(it.fs), ++cnt[it.fs];
}
}
viz[nod] = false;
}
}
int main() {
f >> n >> m;
int a, b, c;
for(int i = 0; i < m; ++i)
f >> a >> b >> c, vec[a].pub(mp(b, c));
bford();
if(negativeCycle)
g << "Ciclu negativ!\n";
else
for(int i = 2; i <= n; ++i)
g << dist[i] << " ";
return 0;
}