Pagini recente » Cod sursa (job #841142) | Cod sursa (job #1248713) | Cod sursa (job #1188405) | Cod sursa (job #620300) | Cod sursa (job #2751710)
#include <bits/stdc++.h>
#define NMAX 50005
#define INF 2000000000
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n,m;
bool negativ;
struct muchie
{
int nod, cost;
};
vector<muchie> v[NMAX];
queue<int> q;
int dist[NMAX];
bool viz[NMAX];
int ap[NMAX];
void Citire()
{
fin>>n>>m;
muchie aux;
for(int i=1; i<=m; i++)
{
int x;
fin>>x>>aux.nod>>aux.cost;
v[x].push_back(aux);
}
for(int i=1; i<=n; i++)
dist[i]=INF;
}
void BellmanFord()
{
dist[1]=0;
viz[1]=1;
ap[1]=1;
q.push(1);
while(!q.empty() && !negativ)
{
int w=q.front();
q.pop();
viz[w]=0;
int dim=v[w].size();
for(int i=0; i<dim; i++)
{
int nod=v[w][i].nod, cost=v[w][i].cost;
if(dist[nod]>dist[w]+cost)
{
dist[nod]=dist[w]+cost;
if(!viz[nod])
{
q.push(nod);
viz[nod]=1;
ap[nod]++;
if(ap[nod]>n)
negativ=1;
}
}
}
}
}
void Afisare()
{
if(negativ)
{
fout<<"Ciclu negativ!";
}
else
{
for(int i=2; i<=n; i++)
{
if(dist[i]==INF)
fout<<"0 ";
else
fout<<dist[i]<<" ";
}
}
}
int main()
{
Citire();
BellmanFord();
Afisare();
return 0;
}