Pagini recente » Cod sursa (job #1154562) | Cod sursa (job #2649686) | Cod sursa (job #1376972) | Cod sursa (job #3041825) | Cod sursa (job #2828076)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int N=5e4;
const int INF=2e9;
const int START=1;
int n,m;
int cont[N + 5];
vector<int> d(N + 5, INF);
vector< pair<int, int> > adj[N + 5];
bitset<N + 5> inQueue;
bool bellmanFord()
{
queue<int> q;
q.push(START);
d[START]=0;
cont[START]=inQueue[START]=1;
while(!q.empty())
{
int nod=q.front();
q.pop();
inQueue[nod]=0;
for(auto x: adj[nod])
{
if(d[nod]+x.second<d[x.first])
{
d[x.first]=d[nod]+x.second;
if(!inQueue[x.first])
{
q.push(x.first);
inQueue[x.first]=1;
cont[x.first]++;
if(cont[x.first]==n)
{
return 0;
}
}
}
}
}
return 1;
}
int main()
{
in>>n>>m;
for(int i=1; i<=m; i++)
{
int x,y,cost;
in>>x>>y>>cost;
adj[x].emplace_back(y, cost);
}
if(!bellmanFord())
{
out<<"Ciclu negativ!";
}
else
{
for(int i=2; i<=n; i++)
{
out<<d[i]<<" ";
}
}
return 0;
}