Pagini recente » Cod sursa (job #1084759) | Cod sursa (job #26162) | Cod sursa (job #270001) | Cod sursa (job #1515662) | Cod sursa (job #2976349)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int nMax=5e4+5;
int n, m, x, y, cost, d[nMax];
vector<pair<int, int>> g[nMax];
bool bellman(int start)
{
queue<int> q;
int fr[nMax]={0};
for(int i=1; i<=n; i++)
d[i]=INT_MAX;
d[start]=0;
q.push(start);
while(!q.empty())
{
int nod=q.front();
q.pop();
fr[nod]++;
if(fr[nod]>n)
return false;
for(auto& i: g[nod])
{
int nodNou=i.first;
int costNou=i.second;
if(d[nodNou] > d[nod]+costNou)
{
d[nodNou]=d[nod]+costNou;
q.push(nodNou);
}
}
}
return true;
}
int main()
{
ios_base::sync_with_stdio(false);
fin.tie(0);
fin>>n>>m;
for(int i=0; i<m; i++)
{
fin>>x>>y>>cost;
g[x].push_back({y, cost});
}
if(!bellman(1))
fout<<"Ciclu negativ!";
else for(int i=2; i<=n; i++)
fout<<d[i]<<' ';
fin.close();
fout.close();
return 0;
}