Pagini recente » Cod sursa (job #3271933) | Cod sursa (job #182141) | Cod sursa (job #278908) | Cod sursa (job #2105415) | Cod sursa (job #2832179)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int N = 500010;
const int oo = 200000010;
int intrari[N], cost[N];
vector<pair<int,int>> adj[N];
queue<int> q;
int n,m, este_ciclu_negativ;
int bellman()
{
q.push(1);
cost[1]=0;
intrari[1] = 1;
while(!q.empty())
{
int nod_curent = q.front();
int cost_curent = cost[nod_curent];
q.pop();
for(auto it : adj[nod_curent])
{
int vecin = it.first;
int cost_vecin = it.second;
if(cost[vecin] > cost_curent + cost_vecin)
{
cost[vecin] = cost_curent + cost_vecin;
q.push(vecin);
intrari[vecin] ++ ;
if(intrari[vecin] >= n)
{
fout<<"Ciclu negativ";
return 1;
}
}
}
}
return 0;
}
int main()
{
fin>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y,cost;
fin>>x>>y>>cost;
adj[x].push_back({y,cost});
}
for(int i=1;i<=n;i++)
cost[i] = oo;
if(bellman())
return 0;
for(int i=2;i<=n;i++)
if(cost[i] == oo)
fout<<"0 ";
else
fout<<cost[i]<<" ";
return 0;
}