Pagini recente » Cod sursa (job #2340109) | Cod sursa (job #1027181) | Cod sursa (job #1323666) | Cod sursa (job #621151) | Cod sursa (job #2236051)
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
#define INF 0x3f3f3f3f
#define Gmax 50010
int dist[Gmax];
int N,M;
struct Graf
{
int from;
int to;
int cost;
}G[Gmax];
int main()
{
f>>N>>M;
for(int i=1; i<=M; i++)
{
int x,y,c;
f>>x>>y>>c;
G[i].from = x;
G[i].to = y;
G[i].cost = c;
}
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
for(int i=0; i<M-1;i++)
{
for(int j=1;j<=N;j++)
{
if(dist[G[j].from] + G[j].cost < dist[G[j].to])
dist[G[j].to] = dist[G[j].from] + G[j].cost;
}
}
for(int i=0; i<M-1;i++)
{
for(int j=1;j<=N;j++)
{
if(dist[G[j].from] + G[j].cost < dist[G[j].to])
dist[G[j].to] = -INF;
}
}
bool negative = false;
for(int i=2; i<=N; i++)
{
if(dist[i]==-INF)
{ g<<"Ciclu negativ!";
negative = true;
break;
}
}
if(!negative)
{
for(int i=2; i<=N; i++)
{
if(dist[i]==INF) g<<0<<' ';
else
g<<dist[i] <<' ';
}
}
return 0;
}