Cod sursa(job #2666712)

Utilizator Dorin07Cuibus Dorin Iosif Dorin07 Data 2 noiembrie 2020 13:54:10
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
#define NMAX 50005
#define INF 2e9
using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

int n, m, x, y, pas;
int path[NMAX], visited[NMAX];
vector < pair< int, int > > nod[NMAX];
queue < int > q;

void read(){
    f>>n>>m;
    for(int i = 1; i <= m; ++i){
        f>>x>>y>>pas;
        nod[x].push_back(make_pair(y, pas));
    }
    for(int i = 2; i <= n; ++i)
        path[i] = INF;
    f.close();
}

void print(){
    for(int i = 2; i <= n; ++i)
        g<<path[i]<<' ';
}

int main()
{
    read();
    int next_node;
    for(int i = 2; i <= n; ++i)
        path[i] = INF;
    path[1] = 0;
    q.push(1);
    while(!q.empty()){
        next_node = q.front();
        visited[next_node]++;
        q.pop();
        if(visited[next_node] > n){
            g<<"Ciclu negativ!";
            return 0;
        }
        for(auto it:nod[next_node])
            if(path[it.first] > path[next_node] + it.second){
                path[it.first] = path[next_node] + it.second;
                q.push(it.first);
            }
    }
    print();
    g.close();
    return 0;
}