Pagini recente » Rating Casian Danut (danutcasian2008) | Cod sursa (job #174226) | Cod sursa (job #3212) | Cod sursa (job #2169647) | Cod sursa (job #1324062)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
vector <int> v[50001];
queue <int> q;
int cost[50001], n, m, x, y, c, ok;
int t[500001];
int bellmanford()
{
cost[1]=0;
q.push(1);
while(!q.empty())
{
int nod = q.front();
for(int k=0; k<v[nod].size(); k+=2)
{
if(cost[v[nod][k]]>cost[nod]+v[nod][k+1])
{
cost[v[nod][k]]=cost[nod]+v[nod][k+1];
t[v[nod][k]]++;
if(t[v[nod][k]]>=n)
return 0;
q.push(v[nod][k]);
}
}
q.pop();
}
return 1;
}
int main()
{
in>>n>>m;
for(int i=0; i<m; i++)
{
in>>x>>y>>c;
v[x].push_back(y);
v[x].push_back(c);
}
for(int i=1; i<=n; i++)
cost[i]=9999999;
ok = bellmanford();
if(ok==0)
out<<"Ciclu negativ!";
else
for(int i=2; i<=n; i++)
out<<cost[i]<<" ";
return 0;
}