Pagini recente » Cod sursa (job #71901) | Cod sursa (job #154105) | Cod sursa (job #2708009) | Cod sursa (job #2427763) | Cod sursa (job #3265389)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define int long long
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int MAX=5e4;
int n,m,i,j,cost,d[MAX+5],fr[MAX+5];
vector <pair<int,int>> muchii[MAX+5];
queue <int> q;
bool in_queue[MAX+5],negative_cycle=0;
signed main()
{
fin>>n>>m;
while (m)
{
fin>>i>>j>>cost;
muchii[i].push_back({j,cost});
m--;
}
for (i=1; i<=n; i++)
d[i]=2e12;
d[1]=0; in_queue[1]=1; fr[1]++; q.push(1);
while (!q.empty() && !negative_cycle)
{
int nod=q.front();
q.pop(); in_queue[nod]=0;
for (auto x: muchii[nod])
{
int nod2=x.first,costmuchie=x.second;
if (d[nod2]>d[nod]+costmuchie)
{
d[nod2]=d[nod]+costmuchie;
if (in_queue[nod2]==0)
{
if (fr[nod2]>n)
{
negative_cycle=1;
break;
}
else
{
q.push(nod2);
fr[nod2]++;
in_queue[nod2]=1;
}
}
}
}
}
if (negative_cycle)
fout<<"Ciclu negativ!";
else
{
for (i=2; i<=n; i++)
fout<<d[i]<<" ";
}
return 0;
}