Cod sursa(job #2432249)

Utilizator Bulboaca_EugenBulboaca Alexandru Eugen Bulboaca_Eugen Data 22 iunie 2019 18:17:43
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5 * 1e4 + 15;
const int INF = 1e8;
struct edge{
    int dest, cost;
};
vector <edge> g[MAXN];
queue <int> q;
int dist[MAXN], introduse[MAXN];
bool ok = true;
void bellman(int n){
    q.push(1);
    while(q.size()){
        int node = q.front();
        q.pop();
        for(auto y : g[node]){
            if(dist[y.dest] > dist[node] + y.cost){
                dist[y.dest] = dist[node] + y.cost;
                q.push(y.dest);
                introduse[y.dest] ++;
                if(introduse[y.dest] == n) {
                    while(q.size()) q.pop();
                    ok = false;
                }
            }
        }
    }
}
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int main(){
    int n, m;
    fin >> n >> m;
    for(int i = 2; i < MAXN; ++i) dist[i] = INF;
    for(int i = 1; i <= m; ++i){
        int a, b, c;
        fin >> a >> b >> c;
        g[a].push_back({b, c});
    }
    bellman(n);
    if(ok) for(int i = 2; i <= n; ++i) fout << dist[i] << " ";
    else fout << "Ciclu negativ!";
    return 0;
}