Pagini recente » Cod sursa (job #3178230) | Cod sursa (job #1252508) | Cod sursa (job #1332638) | Cod sursa (job #1556454) | Cod sursa (job #1596753)
#include <cstdio>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;
#define Nmax 50010
vector <pair<long,long> >ad[Nmax] ;
queue <long> q ;
long T[Nmax] , n , m , x , y , c , cnt_in_queue[Nmax];
bool in_queue[Nmax] , negativ ;
void BellManFord ( long start )
{
q.push(start);
in_queue[start] = true ;
memset(T,0x3f,sizeof(T)) ;
T[start] = 0 ;
while ( !q.empty() )
{
long nod = q.front();
q.pop();
in_queue[nod] = false ;
negativ = false ;
for ( long i = 0 ; i < ad[nod].size() ; ++i )
{
if ( T[nod] + ad[nod][i].second < T[ad[nod][i].first] )
{
T[ad[nod][i].first] = T[nod] + ad[nod][i].second ;
if ( !in_queue[ad[nod][i].first] )
{
{
q.push(ad[nod][i].first) ;
in_queue[ad[nod][i].first] = true ;
}
}
}
else negativ = true ;
}
}
}
int main()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
scanf("%d %d",&n,&m);
for ( long i = 1 ; i <= m ; i++ )
{
scanf("%d %d %d",&x,&y,&c);
ad[x].push_back(make_pair(y,c));
}
BellManFord(1) ;
if ( negativ == true )
{
printf("Ciclu negativ!\n");
return 0 ;
}
for ( long i = 2 ; i <= n ; i++ )
{
printf("%d ",T[i]) ;
}
}