Pagini recente » Rating Ceapa Delia Ioana (delia_ioana) | Cod sursa (job #1731894)
#define N 50050
#include <queue>
#include <stdio.h>
#include <vector>
#define inf 1000000
using namespace std;
vector <pair <int ,int> > drum[N];
queue <pair <int , int> > q;
int n ,m;
int viz[N];
int distanta[N];
void read()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
scanf("%d %d",&n,&m);
int a,b,c;
for(int i = 2 ; i <= n ; i++)
distanta[i] = inf;
for(int i = 1 ; i <= m ; i++)
{
scanf("%d %d",&a,&b,&c);
drum[a].push_back(make_pair(b,c));
}
}
void bellmanford()
{
q.push(make_pair(0,1));
while(!q.empty())
{
int cost = q.front().first;
int b = q.front().second;
q.pop();
for(vector <pair <int , int > > :: iterator it = drum[b].begin() ; it != drum[b].end() ; ++it)
{
if(cost+it->second < dist[it->first])
{
distanta[it->first]= cost + it->second;
viz[it->first]++;
if(viz[it->first] > n)
{
printf("Ciclu negativ!");
return;
}
q.push(make_pair(distanta[it->first], it->first));
}
}
}
for(int i = 2; i <= n ; i++)
printf("%d ",distanta[i]);
}
int main()
{
read();
bellmanford();
return 0;
}