Pagini recente » Cod sursa (job #738445) | Cod sursa (job #2286715) | Cod sursa (job #383638) | Cod sursa (job #856624) | Cod sursa (job #1921790)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMAX=50001, inf=(1<<25);
vector< pair<int, int> > g[NMAX];
queue< int> q;
int vis[NMAX], d[NMAX], n, m;
int bellmanford()
{
for(int i=2; i<=n; i++)
d[i]=inf;
while(!q.empty())
{
int x=q.front();
q.pop();
vis[x]++;
if(vis[x]>=n)
return -1;
for(vector< pair<int, int> >::iterator it=g[x].begin(); it!=g[x].end(); it++)
if(d[it->first]>d[x]+it->second)
{
d[it->first]=d[x]+it->second;
q.push(it->first);
}
}
return 1;
}
int main()
{
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
cin>>n>>m;
for(int i=1; i<=m; i++)
{
int u, v, c;
cin>>u>>v>>c;
g[u].push_back(make_pair(v, c));
}
q.push(1);
if(bellmanford()<0)
cout<<"Ciclu negativ!";
else
for(int i=2; i<=n; i++)
cout<<d[i]<<' ';
return 0;
}