Pagini recente » Cod sursa (job #849931) | Cod sursa (job #1750467) | Cod sursa (job #485893) | Cod sursa (job #1668445) | Cod sursa (job #2964985)
#include <fstream>
#include <vector>
#include <queue>
const int NMAX=50005;
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector< pair< int, int > > v[NMAX];
queue< pair< int, int > > q; //{cost, nod}
int dmin[NMAX], in[NMAX];
bool uz[NMAX];
int n, p, m;
void bellman(int);
int main()
{
ios_base::sync_with_stdio(false);
fin.tie(0);
fout.tie(0);
int i, a, b, c;
fin>>n>>m;
for(i=1; i<=m; i++)
{
fin>>a>>b>>c;
v[a].push_back(make_pair(b, c));
}
for(i=2; i<=n; i++) dmin[i]=2e9;
bellman(1);
return 0;
}
void bellman(int nod)
{
int i;
pair <int, int> p;
q.push({0, nod});
while(!q.empty())
{
p=q.front();
for(auto i:v[p.second])
{
if(dmin[i.first]>dmin[p.second]+i.second)
{
in[i.first]++;
if(in[i.first]>=n+1)
{
fout<<"Ciclu negativ!"<<'\n';
return;
}
dmin[i.first]=dmin[p.second]+i.second;
q.push({dmin[i.first], i.first});
}
}
q.pop();
}
for(i=2; i<=n; i++) fout<<dmin[i]<<' ';
return;
}