Pagini recente » Cod sursa (job #1493927) | Cod sursa (job #1091296) | Cod sursa (job #1766368) | Cod sursa (job #60696) | Cod sursa (job #1318496)
#include <fstream>
#include <list>
#include <queue>
#define DIM 50001
#define INF 999999
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m,x,y,c,d[DIM],count[DIM];
list<pair <int,int> > nod[DIM];
queue<int> cd;
void bellmanford(int k)
{
cd.push(k);
while(!cd.empty())
{
int vf=cd.front();
for(list<pair <int,int> >::iterator i=nod[vf].begin();i!=nod[vf].end();++i)
{
std::pair<int, int> q=*i;
if(d[vf]+ q.second<d[q.first])
{
d[q.first]=d[vf]+ q.second;
count[q.first]++;
if(count[q.first] >n)
{
g<<"Ciclu negativ!\n";
return;
}
cd.push(q.first);
}
}
cd.pop();
}
for(int i=2;i<=n;++i)
g<<d[i]<<" ";
g<<'\n';
}
int main()
{
f>>n>>m;
for(int i=1;i<=m;++i)
{
f>>x>>y>>c;
nod[x].push_back(make_pair(y,c));
}
for(int i=2;i<=n;++i)
d[i]=INF;
bellmanford(1);
f.close();
g.close();
return 0;
}