Pagini recente » Cod sursa (job #1816548) | Cod sursa (job #660401) | Cod sursa (job #516010) | Cod sursa (job #516115) | Cod sursa (job #1131250)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#define inf 10000000
#define nmax 50005
using namespace std;
vector <int>v[nmax],s[nmax];
int n,m,x,y,c,dist[nmax],nr[nmax];
queue <int>q;
bool ok;
void bellmanford()
{
for(int i=2; i<=n; i++)dist[i]=inf;
dist[1]=0;
q.push(1);
while(!q.empty())
{
int x=q.front();
for(int i=0; i<v[x].size(); i++)
if(dist[x]+s[x][i]<dist[v[x][i]])
{
dist[v[x][i]]=s[x][i]+dist[x];
nr[v[x][i]]++;
q.push(v[x][i]);
if(nr[v[x][i]]>n)ok=true;
}
q.pop();
}
}
int main()
{
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
f>>n>>m;
for(int i=1; i<=m; i++)
{
f>>x>>y>>c;
v[x].push_back(y);
s[x].push_back(c);
}
bellmanford();
if(ok==true)g<<"Ciclu Negati";
else
for(int i=2; i<=n; i++)
if(dist[i]==inf)g<<"0 ";
else g<<dist[i]<<" ";
return 0;
}