Pagini recente » Cod sursa (job #3268557) | Cod sursa (job #2591976) | Cod sursa (job #599256) | Cod sursa (job #1393822) | Cod sursa (job #3284195)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int Nmax=50005;
long long cost[Nmax];
vector<pair<long long,long long>>v[Nmax];
int viz[Nmax];
bitset<Nmax> inq;
queue<int>q;
int main()
{
int n,m;
fin>>n>>m;
long long x,y,c;
for(int i=1;i<=m;i++)
{
fin>>x>>y>>c;
v[x].push_back({y,c});
}
for(int i=1;i<=n;i++) cost[i]=LLONG_MAX;
q.push(1);
inq[1]=1;
cost[1]=0;
while(!q.empty())
{
long long nod=q.front();
inq[nod]=0;
q.pop();
for(int i=0;i<v[nod].size();i++)
{
long long next=v[nod][i].first;
long long ct=v[nod][i].second;
if(cost[next]>ct+cost[nod])
{
cost[next]=cost[nod]+ct;
viz[next]++;
if(!inq[next])
{
q.push(next);
inq[next]=1;
}
}
if(viz[next]>n)
{
fout<<"Ciclu negativ!";
return 0;
}
}
}
for(int i=2;i<=n;i++)
{
fout<<cost[i]<<' ';
}
return 0;
}