Pagini recente » Cod sursa (job #2750891) | Cod sursa (job #1767891) | Cod sursa (job #2497961) | Cod sursa (job #1150819) | Cod sursa (job #2853168)
#include <iostream>
#include <fstream>
#include <queue>
#include<vector>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
int n,m;
int fr[50001],dist[50001];
queue<pair<int,int>>q;
vector<pair<int,int>>adiacenta[50001];
void citire()
{
f >> n >> m;
for(int i = 1; i<=m; i++)
{
int x,y,c;
f >> x >> y >> c;
adiacenta[x].push_back({y,c});
}
}
void init()
{
for(int i = 1; i<=n; i++)
dist[i] = (1<<30)-1;
}
void bellman()
{
q.push({0,1});
fr[1] = 1;
dist[1] = 0;
while(!q.empty())
{
int nod_curent = q.front().second;
int cost_curent = q.front().first;
q.pop();
for(auto x:adiacenta[nod_curent])
{
int vecin = x.first;
int cost = x.second;
if(dist[vecin]>dist[nod_curent]+cost)
{
dist[vecin] = cost+dist[nod_curent];
fr[vecin]++;
q.push({dist[vecin],vecin});
}
if(fr[vecin]>=n+1)
{
g << "Ciclu negativ!";
exit(0);
}
}
}
}
void afisare()
{
for(int i = 2; i<=n; i++)
g << dist[i]<< " ";
}
int main()
{
citire();
init();
bellman();
afisare();
}