Pagini recente » Cod sursa (job #28997) | Cod sursa (job #1818209) | Cod sursa (job #2989844)
#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});
//v[y].push_back({x, c});
}
}
bool bford(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(bford(1))g<<"Ciclu negativ!";
else for(int i=2; i<=n; i++)g<<d[i]<<" ";
}
int main()
{
citire();
rez();
return 0;
}