Cod sursa(job #2979381)

Utilizator maiaauUngureanu Maia maiaau Data 14 februarie 2023 23:35:27
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back

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

const int N = 5e4 + 5;
const int oo = 1e9;

int n, cnt[N], cmin[N];
vector<pair<int, int>> v[N];
queue<pair<int, int>> q;

void read();

int main()
{
    read();
    q.push({1, 0});
    while (!q.empty()){
        int nod, cost;
        tie(nod, cost) = q.front(); q.pop();
        for (auto it: v[nod]){
            int to, c; tie(to, c) = it;
            if (cmin[to] > c + cost){
                cmin[to] = c + cost;
                cnt[to]++; q.push({to, cmin[to]});
                if (cnt[to] > n + 1){
                    g << "Ciclu negativ!";
                    return 0;
                }
            }
        }
    }
    for (int i = 2; i <= n; i++) g << cmin[i] << ' ';

    return 0;
}

void read(){
    int m, a, b, c;
    f >> n >> m;
    for (int i = 1; i <= n; i++) cmin[i] = oo;
    for (; m; m--){
        f >> a >> b >> c;
        v[a].pb({b, c});
    }
}