Pagini recente » Cod sursa (job #2490612) | Cod sursa (job #3219498) | Cod sursa (job #856882) | Cod sursa (job #876378) | Cod sursa (job #3001198)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m,viz[50001],d[50001];
vector<pair<int,int>>v[50001];
void citire()
{
f>>n>>m;
for(int i=1; i<=m; i++)
{
int x,y,c;
f>>x>>y>>c;
v[x].push_back({y,c});
}
}
bool bellmanford(int vf)
{
queue<int>q;
for(int i=1;i<=n;i++)
d[i]=INT_MAX,viz[i]=0;
d[vf]=0;
viz[vf]=1;
q.push(vf);
while(!q.empty())
{
int x=q.front();
q.pop();
viz[x]++;
if(viz[x]==n)return true;
for(auto i:v[x])
{
int vcn=i.first, cst=i.second;
if(d[x]+cst<d[vcn])
{
d[vcn]=d[x]+cst;
q.push(vcn);
}
}
}
return false;
}
void rez()
{
if(bellmanford(1))
g<<"Ciclu negativ!";
else
for(int i=2;i<=n;i++)
g<<d[i]<<" ";
}
int main()
{
citire();
rez();
return 0;
}