Cod sursa(job #2907013)

Utilizator bluestorm57Vasile T bluestorm57 Data 28 mai 2022 14:21:43
Problema Algoritmul Bellman-Ford Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
/// 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(1);
    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;
}