Pagini recente » Cod sursa (job #1410941) | Cod sursa (job #118809) | Cod sursa (job #2901258) | Cod sursa (job #2714730) | Cod sursa (job #662155)
Cod sursa(job #662155)
#include<cstdio>
#include<queue>
#include<vector>
#include<bitset>
#include<cstring>
using namespace std;
const int Max_N = 50100;
const int INF = 0x3f3f3f3f;
const char in[] = "bellmanford.in";
const char out[]= "bellmanford.out";
#define pb push_back
vector<int>G[Max_N], C[Max_N];
queue<int>Q;
int dist[Max_N], cnt_Q[Max_N], N, M;
bool in_Q[Max_N], ciclu_negativ;
int main()
{
freopen(in,"r",stdin);
freopen(out,"w",stdout);
scanf("%d %d", &N, &M);
memset(dist, INF, sizeof(dist));
int a, b, cost, x;
for(int i = 1 ; i <= M ; ++i)
scanf("%d%d%d", &a, &b, &cost), G[a].pb(b), C[a].pb(cost);
dist[1] = 0, Q.push(1), in_Q[1] = true;
while( Q.size() && !ciclu_negativ )
{
x = Q.front();
Q.pop();
in_Q[x] = false;
for(int i = 0 ; i < G[x].size() ; ++i)
{
if(dist[G[x][i]] > dist[x] + C[x][i])
{
dist[G[x][i]] = dist[x] + C[x][i];
if(!in_Q[G[x][i]])
if(cnt_Q[G[x][i]] > N)ciclu_negativ = true;
else
{
Q.push(G[x][i]);
in_Q[G[x][i]] = true;
++cnt_Q[G[x][i]];
}
}
}
}
if(ciclu_negativ)printf("Ciclu negativ!");
else
for(int i = 2 ; i <= N ; ++i)
printf("%d ", dist[i]);
return 0;
}