Pagini recente » Cod sursa (job #387959) | Cod sursa (job #1454465) | Cod sursa (job #2265702) | Cod sursa (job #2930165) | Cod sursa (job #2819259)
#define MAX 0x3f3f3f3f
#define NMAX 50005
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
int n,m;
int intrari_in_queue[NMAX], viz[NMAX];
int cost[NMAX];
vector<pair<int,int>> adiacenta[NMAX];
queue<int> q;
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;
viz[1] = 1;
while(!q.empty())
{
int nod_curent = q.front();
int cost_curent = cost[nod_curent];
q.pop();
viz[nod_curent] = 0;
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;
if(viz[vecin] == 0)
{
q.push(vecin);
viz[vecin] = 1;
}
intrari_in_queue[vecin]++;
if(intrari_in_queue[vecin]>=n)
{
g<<"Ciclu negativ!";
return 1;
}
}
}
}
return 0;
}
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();
}