Pagini recente » Cod sursa (job #32562) | Cod sursa (job #145493) | Cod sursa (job #410775) | Cod sursa (job #3159101) | Cod sursa (job #2683135)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define nmax 50001
#define inf 1e9
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,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;
}