Pagini recente » Cod sursa (job #729172) | Cod sursa (job #216007) | Cod sursa (job #645440) | Cod sursa (job #1407865) | Cod sursa (job #1564359)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
bitset<50001> inn;
vector<int> V[50001],C[50001];
queue<int> q;
int d[50001],apinn[50001],n,ciclun,haha=1000000000;
void belli()
{
int x,e,c;
d[1] = 0;
q.push(1);
inn[1] =1;
while (!q.empty() and !ciclun)
{
x=q.front();
q.pop();
inn[x]=0;
for (size_t i=0;i<V[x].size();i++)
{
e=V[x][i]; c=C[x][i];
if(d[e]>d[x]+c)
{
d[e]=d[x]+c;
if(!inn[e])
{if(apinn[e]>=n)
ciclun=1;
else
{
q.push(e);
inn[e]=1;
apinn[e]++;
}}
}
}
}
}
int main()
{
int m,x,y,c,i;
f>>n>>m;
for (i=1;i<=m;i++)
{
f>>x>>y;
V[x].push_back(y);
f>>c;
C[x].push_back(c);
}
for(i=2;i<=n;i++)
d[i]=haha;
belli();
if(!ciclun)
for (i=2;i<=n;i++)
g<<d[i]<<" ";
else g<<"Ciclu negativ!";
return 0;
}