Pagini recente » Cod sursa (job #2522579) | Cod sursa (job #2777477) | Cod sursa (job #1873600) | Cod sursa (job #2648200) | Cod sursa (job #2030237)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <string.h>
#define inf 0x3f3f3f3f
#define NMAX 5001
using namespace std;
int n,m;
vector< pair<int,int > > g[NMAX];
queue<int> q;
bitset<NMAX> viz;
int d[NMAX]; ///distance
int counter[NMAX];
void citire()
{
scanf("%d %d",&n,&m);
int x,y,c;
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&x,&y,&c);
g[x].push_back(make_pair(y,c));
}
}
void bellman()
{
memset(d,inf,sizeof(d));
q.push(1);
d[1] = 0;
while(!q.empty())
{
int top = q.front();
q.pop();
viz[top] = 0;
for( vector<pair<int,int> >::iterator it = g[top].begin(); it!=g[top].end(); it++)
{
if( d[(*it).first] > d[top] + (*it).second )
{
if(++counter[top] == n)
{
printf("Ciclu negativ!");
return;
}
if(!viz[(*it).first])
{
q.push((*it).first);
viz[(*it).first] = 1;
d[(*it).first] = d[top] + (*it).second;
}
}
}
}
}
void afisare()
{
for(int i=2;i<=n;i++)
printf("%d ",d[i]);
}
int main()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
citire();
bellman();
afisare();
return 0;
}