Pagini recente » Cod sursa (job #2556014) | Cod sursa (job #2052223) | Cod sursa (job #1456632) | Cod sursa (job #1011134) | Cod sursa (job #2907014)
/// Testing
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
const int inf = 1e9;
const int NMAX = 5e4 + 10;
vector < pair < int, int > > v[NMAX];
int n,m;
int h[NMAX], dist[NMAX], checked[NMAX], viz[NMAX];
int main(){
f >> n >> m;
while(m--){
int x, y, z;
f >> x >> y >> z;
v[x].push_back({y, z});
}
for(int i = 1 ; i <= n ; i++){
h[i] = inf;
dist[i] = inf;
v[0].push_back({i, 0});
}
deque < int > q;
q.push_back(0);
while(!q.empty()){
int node = q.front();
q.pop_front();
for(const auto &it: v[node])
if(h[it.first] > h[node] + it.second){
checked[it.first] = checked[node] + 1;
if(checked[it.first] > n + 2){
g << "Ciclu negativ!";
return 0;
}
h[it.first] = h[node] + it.second;
q.push_back(it.first);
}
}
for(int i = 1 ; i <= n ; i++)
for(auto &it: v[i])
it.second += h[i] - h[it.first];
priority_queue < pair < int, int > > d;
dist[1] = 0;
d.push({0, 1});
while(!d.empty()){
int node = d.top().second;
d.pop();
if(viz[node])
continue;
viz[node] = 1;
for(const auto &it: v[node])
if(dist[it.first] > dist[node] + it.second){
dist[it.first] = dist[node] + it.second;
d.push({-dist[it.first], it.first});
}
}
for(int i = 2 ; i <= n ; i++)
g << dist[i] - h[1] + h[i] << " " ;
return 0;
}