Pagini recente » Cod sursa (job #593736) | Cod sursa (job #2973472) | Cod sursa (job #1141363) | Cod sursa (job #1832219) | Cod sursa (job #1849973)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define N 50010
#define INF 2000000001
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector<pair<int,int> > vec[N];
bool Queue[N];
int dist[N],i,j,n,m,k,cunt[N],r,t;
bool negative_cycle=false;
int main()
{
int from,to,cost;
f>>n>>m;
while(m!=0)
{
f>>from>>to>>cost;
vec[from].push_back(make_pair(to,cost));
m--;
}
for(i=1;i<=n;i++)
dist[i]=INF;
dist[1]=0;
Queue[1]=true;
queue<int> q;
q.push(1);
int nod;
while(!q.empty() && !negative_cycle)
{
nod=q.front();
Queue[nod]=false;
q.pop();
for(vector<pair<int,int> >::iterator it=vec[nod].begin();it!=vec[nod].end();++it)
{
to=it->first;
cost=it->second;
if(dist[to]>dist[nod]+cost)
{
dist[to]=dist[nod]+cost;
if(!Queue[to])
{
if(cunt[to]>n)
{
negative_cycle=true;
}
else
{
Queue[to]=true;
q.push(to);
cunt[to]++;
}
}
}
}
}
if(negative_cycle==true)
{
g<<"Ciclu negativ!";
}
else
{
for(i=2;i<=n;i++)
g<<dist[i]<<' ';
}
}