Pagini recente » Cod sursa (job #1869703) | Cod sursa (job #2812432) | Cod sursa (job #1339564) | Cod sursa (job #1349900) | Cod sursa (job #3266849)
#include <bits/stdc++.h>
using namespace std;
vector<int> bellman(int n, vector<int> sources, vector<vector<pair<int, int>>> graph)
{
const int INF = 2e9;
queue<int> q;
vector<int> dist(n + 1, INF);
vector<int> nrnd(n + 1, 0);
for(auto it = sources.begin(); it != sources.end(); it++)
{
q.push((*it));
dist[(*it)] = 0;
nrnd[(*it)] = 1;
}
while(!q.empty())
{
int nd = q.front();
q.pop();
if(nrnd[nd] > n)
return vector<int>(1, -1);
for(auto it = graph[nd].begin(); it != graph[nd].end(); it++)
{
if(dist[(*it).first] > dist[nd] + (*it).second)
{
dist[(*it).first] = dist[nd] + (*it).second;
nrnd[(*it).first] = nrnd[nd] + 1;
q.push((*it).first);
}
}
}
return dist;
}
int main()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
int n, m;
cin >> n >> m;
vector<vector<pair<int, int>>> graph(n + 1);
for(int i = 0; i < m; i++)
{
int x, y, c;
cin >> x >> y >> c;
graph[x].push_back({y, c});
}
vector<int> dist;
dist = bellman(n, vector<int>(1, 1), graph);
if(dist.size() == 1)
cout << "Ciclu negativ!";
else
{
for(auto it = dist.begin() + 2; it != dist.end(); it++)
{
cout << (*it) << " ";
}
}
}