Pagini recente » Cod sursa (job #2784121) | Cod sursa (job #2132490) | Cod sursa (job #572467) | Cod sursa (job #1690356) | Cod sursa (job #2819255)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define MAX (1<<30)-1
#define NMAX 50005
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
int intrari_in_queue[NMAX];
int cost[NMAX];
vector<pair<int,int>>adiacenta[NMAX];
queue<int>q;
int n,m;
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++)
cost[i] = MAX;
}
bool Bellman()
{
q.push(1);
cost[1] = 0;
intrari_in_queue[1] = 1;
while(!q.empty())
{
int nod_curent = q.front();
int cost_curent = cost[nod_curent];
q.pop();
for(auto x:adiacenta[nod_curent])
{
int vecin = x.first;
int cost_vecin = x.second;
if(cost[vecin]>cost_curent+cost_vecin)
{
cost[vecin] = cost_curent+cost_vecin;
q.push(vecin);
intrari_in_queue[vecin]++;
}
if(intrari_in_queue[vecin]>=n)
{
g<<"Ciclu negativ!";
return 1;
}
}
}
}
void afisare()
{
for (int i = 2; i <= n; i++)
{
if (cost[i] == MAX)
{
g << "0 ";
}
else
g << cost[i] << " ";
}
}
int main()
{
citire();
init();
if(Bellman())
{
return 0;
}
afisare();
return 0;
}