Pagini recente » Cod sursa (job #2062629) | Cod sursa (job #61169) | Cod sursa (job #416582) | Cod sursa (job #847774) | Cod sursa (job #2718317)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fi("bellmanford.in");
ofstream fo("bellmanford.out");
int n,m,i,j,c,k,d[50001], nrap[50001];
const int inf = 1<<29;
vector<pair<int,int>>v[50001];
queue<int>q;
bool vz[50001], negativ;
void BellmanFord( bool &negativ)
{
int i,x,nod,cost;
size_t j;
negativ = false;
for(i=1; i<=n; i++)
d[i] = inf;
d[1] = 0;
q.push(1);
vz[1] = true;
while(!q.empty() && !negativ)
{
x = q.front();
q.pop();
vz[x] = false;
for(j=0; j<v[x].size(); j++)
{
nod = v[x][j].first;
cost = v[x][j].second;
if(d[nod] > d[x] + cost)
{
d[nod] = d[x] + cost;
if(!vz[nod])
{
if(nrap[nod] > n)
negativ = true;
else
{
q.push(nod);
vz[nod] = true;
nrap[nod]++;
}
}
}
}
}
}
int main()
{
fi >> n >> m;
for(k=1; k<=m; k++)
{
fi >> i >> j >> c;
v[i].push_back(make_pair(j,c));
}
BellmanFord(negativ);
if(negativ)
{
fo << "Ciclu negativ!";
}
else
{
for(i=2; i<=n; i++)
fo << d[i] << " ";
}
}