Cod sursa(job #3215859)

Utilizator maiaauUngureanu Maia maiaau Data 15 martie 2024 13:44:08
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
using namespace std;
using pii = pair<int,int>;
#define pb push_back

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

const int N = 50005;
const int oo = 0x3f3f3f3f;

int n;
vector<int> c, cnt;
vector<vector<pii>> e;

void read(), bellmanford();

int main(){
    read();
    bellmanford();
    for (int i = 2; i <= n; i++)
        fout << c[i] << ' ';

    return 0;
}
void read(){
    int m; fin >> n >> m;
    e.resize(n+2); c.resize(n+2, oo); cnt.resize(n+2);
    while (m--){
        int a, b, k; fin >> a >> b >> k;
        e[a].pb({b, k});
    }
}
void bellmanford(){
    queue<pii> s; s.push({0, 1}); c[1] = 0;
    while (!s.empty()){
        int cst, from; 
        tie(cst, from) = s.front();
        s.pop();
        for (auto it: e[from]){
            int to, cm; tie(to, cm) = it;
            if (cm + cst < c[to]){
                cnt[to]++;
                if (cnt[to] == n+2){
                    fout << "Ciclu negativ!";
                    exit(0);
                }
                c[to] = cst + cm;
                s.push({c[to], to});
            }
        }
    }
}