Cod sursa(job #2329631)

Utilizator netfreeAndrei Muntean netfree Data 27 ianuarie 2019 09:20:24
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
#define pii pair<int, int>
#define x first
#define y second

using namespace std;

ifstream fin ("bellmanford.in");
ofstream fout("bellmanford.out");

const int N_MAX = 50000 + 5;
const int INF = 0x3f3f3f3f;

vector<pii> vec[N_MAX];
int costs[N_MAX], viz[N_MAX];
queue<int> q;

int n, m;

int main()
{
    fin >> n >> m;
    while(m--){
        int a, b, c;
        fin >> a >> b >> c;
        vec[a].push_back({b,c});
    }

    for(int i = 1; i<=n; ++i)
        costs[i] = INF;

    costs[1] = 0;
    q.push(1);
    while(!q.empty()){
        int node = q.front();
        q.pop();

        viz[node]++;

        if(viz[node] > n){
            fout << "Ciclu negativ!";
            return 0;
        }

        for(auto v : vec[node]){
            if(costs[v.x] > costs[node] + v.y){
                costs[v.x] = costs[node] + v.y;
                q.push(v.x);
            }
        }
    }

    for (int i=2; i<=n; i++)
        fout<<costs[i]<<' ';


    return 0;
}