Pagini recente » Cod sursa (job #1131939) | Cod sursa (job #2871782) | Cod sursa (job #1515011) | Cod sursa (job #2556527) | Cod sursa (job #2819245)
#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;
intrari_in_queue[1] = 1;
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])
{
if(cost[x.first] > cost_curent+x.second)
{
cost[x.first] = cost_curent + x.second;
if(viz[x.first] == 0)
{
q.push(x.first);
viz[x.first] = 1;
}
intrari_in_queue[x.first]++;
if(intrari_in_queue[x.first]>=n)
{
g<<"Ciclu negativ!";
exit(0);
}
}
}
}
}
void afisare()
{
for (int i = 2; i <= n; i++)
{
if (cost[i] >= MAX)
g << "0 ";
else
g << cost[i] << " ";
}
}
int main()
{
citire();
init();
Bellman();
afisare();
}