Pagini recente » Cod sursa (job #612247) | Cod sursa (job #84854) | Cod sursa (job #1397181)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMax = 50002;
const int INF = (1<<30) + 1 ;
vector< pair<int,int> > G[NMax];
int d1[NMax];
int nr[NMax];
int n,m;
bool negativ = 0;
void bellman()
{
int from;
queue<int> Q;
Q.push(1);
for(int i = 1; i <= n; i++) d1[i] = INF;
d1[1] = 0;
while(!Q.empty() && !negativ)
{
from = Q.front();
Q.pop();
for( auto it = G[from].begin(); it != G[from].end(); it++)
{
//cerr<<"da";
if(d1[it->first] > d1[from] + it->second)
{
// cerr<<"yes";
d1[it->first] = d1[from] + it->second;
Q.push(it->first);
nr[it->first]++;
}
if(nr[it->first] > n) negativ =1;
}
}
}
int main()
{
int x,y,c;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
f>>n>>m;
for(int i = 1; i <= m ;i++)
{
f>>x>>y>>c;
G[x].push_back(make_pair(y,c));
}
// cerr<<INF;
bellman();
if(negativ)
{
g<<"Ciclu negativ!";
}
else
{
for(int i = 2; i <= n ;i++)
{
g<<d1[i]<<" ";
}
}
}