Pagini recente » Cod sursa (job #50013) | Cod sursa (job #2713553) | Cod sursa (job #1983613) | Cod sursa (job #2954275) | Cod sursa (job #2572381)
#include <iostream>
#include <fstream>
#define nmax 50001
#define inf 1e9
#include <vector>
#include <queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector<pair<int,int> > v[nmax];
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > >h;
int d[nmax],n,m,a,b,c,nod;
int w[nmax];
int main()
{
int i;
f>>n>>m;
for(i=1; i<=m; i++)
{
f>>a>>b>>c;
v[a].push_back(make_pair(c,b));
}
for(i=1; i<=n; i++)
d[i]=inf;
d[1]=0;
h.push(make_pair(0,1));
while(!h.empty())
{
nod=h.top().second;
h.pop();
for(i=0; i<v[nod].size(); i++)
{
if(d[nod]+v[nod][i].first<d[v[nod][i].second])
{
w[v[nod][i].second]++;
d[v[nod][i].second]=d[nod]+v[nod][i].first;
h.push(make_pair(d[v[nod][i].second],v[nod][i].second));
if(w[v[nod][i].second]==n)
{
g<<"Ciclu negativ!";
return 0;
}
}
}
}
for(i=2; i<=n; i++)
{
g<<d[i]<<" ";
}
return 0;
}