Pagini recente » Cod sursa (job #595234) | Cod sursa (job #2709689) | Cod sursa (job #930875) | Cod sursa (job #2889592) | Cod sursa (job #2575361)
#include <bits/stdc++.h>
#define nMax 50005
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int INF=1e9;
int n, m, a, b, dist, ok, d[nMax], nr[nMax];
vector<pair<int, int>> G[nMax];
queue<int> Q;
bitset<nMax> in;
void bf(int nod)
{
for(int i=2; i<=n; i++)
d[i]=INF;
d[nod]=0;
Q.push(nod);
in[nod]=1;
while(!Q.empty())
{
nod=Q.front();
Q.pop();
in[nod]=0;
for(auto i:G[nod])
if(d[nod]+i.second<d[i.first])
{
d[i.first]=d[nod]+i.second;
nr[i.first]++;
if(nr[i.first]>n)
{
ok=1;
return;
}
if(!in[i.first])
{
in[i.first]=1;
Q.push(i.first);
}
}
}
}
int main()
{
fin >> n >> m;
for(int i=1; i<=m; i++)
{
fin >> a >> b >> dist;
G[a].push_back({b, dist});
}
bf(1);
if(!ok)
for(int i=2; i<=n; i++)
fout << d[i] << " ";
else
fout << "Ciclu negativ!";
return 0;
}