Pagini recente » Cod sursa (job #564231) | Cod sursa (job #3002017) | Cod sursa (job #2409856) | Cod sursa (job #991102) | Cod sursa (job #3335952)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int N = 50007;
int n,m;
vector<pair<int, int>> a[N];
vector<int> dist(N, 0), viz(N, 0), updated(N, 0);
bool ciclu_negativ;
void calc_dist()
{
queue<int> q;
viz[1] = 1;
updated[1] = 0;
for(int step = 1; step <= n; step++)
{
bool modif = 0;
for(int x = 1; x <= n; x++)
if(viz[x] and updated[x] == step - 1)
for(auto pw : a[x])
{
int y = pw.second;
int c = pw.first;
if(!viz[y] or dist[y] > dist[x] + c)
{
dist[y] = c + dist[x];
viz[y] = 1;
updated[y] = step;
modif = 1;
}
}
if(modif and step == n)
ciclu_negativ = 1;
}
}
int main()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, c;
fin >> x >> y >> c;
a[x].push_back({c, y});
}
calc_dist();
if(ciclu_negativ)
fout << "Ciclu negativ!" ;
else
for (int i = 2; i <= n; i++)
if (dist[i] == -1)
fout << "0 ";
else
fout << dist[i] << " ";
return 0;
}