Pagini recente » Cod sursa (job #2252803) | Cod sursa (job #1861274) | Cod sursa (job #2100677) | Cod sursa (job #2514926) | Cod sursa (job #2176166)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<pair<int, int > > v[50005];
int n, a, m, aux, nr, b, c,freq[50005], cost[50005] ,inf=999999999;
queue <int> q;
pair <int, int>x;
int main()
{
fin>>n>>m;
for(int i=1; i<=m; i++)
{
fin>>a>>b>>c;
v[a].push_back(make_pair(b,c));
}
for(int i=2; i<=n; i++)
cost[i]=inf;
q.push(1);
while(!q.empty())
{
int aux=q.front();
if(freq[aux]>n)
{
fout<<"Ciclu negativ!";
return 0;
}
q.pop();
for(int i=0; i<v[aux].size(); i++)
{
x=v[aux][i];
if(cost[x.first]>cost[aux]+x.second)
{
cost[x.first]=cost[aux]+x.second;
q.push(x.first);
freq[x.first]++;
}
}
}
for(int i=2; i<=n; i++)
fout<<cost[i]<<" ";
return 0;
}