Cod sursa(job #2896790)

Utilizator VDAVIDVladuca david VDAVID Data 30 aprilie 2022 20:08:40
Problema Algoritmul Bellman-Ford Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <bits/stdc++.h>

using namespace std;

int n, a[5001][5001], m, v[5001], ok;

void dijikstra() {
    vector<int> f(101);
    queue<int> q;
    q.push(1);
    v[1] = 0;
    while(!q.empty()) {
        int nod = q.front();
        q.pop();
        if(f[nod] >= n) {
            ok = 1;
            return;
        }
        f[nod]++;
        //cout << v[nod] << ' ';
        for(int i = 1; i <= n; i++) {
            //cout << v[i] << ' ';
            if(a[nod][i] && v[nod] + a[nod][i] < v[i])
                v[i] = a[nod][i] + v[nod], q.push(i);
        }
    }
}

int main() {
    ifstream cin("bellmanford.in");
    ofstream cout("bellmanford.out");
    int p;
    cin >> n >> p;
    int x, y, k;
    while(cin >> x >> y >> k)
        a[x][y] = k;

    for(int i = 1; i <= n; i++)
        v[i] = INT_MAX / 2 - 1;
    dijikstra();

    if(ok) {
        cout << "Ciclu negativ!";
        return 0;
    }
    for(int i = 2; i <= n; i++)
        cout << v[i] << ' ';
    return 0;
}