Cod sursa(job #2525668)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 17 ianuarie 2020 17:32:15
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>
using namespace std;

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

vector< pair< int, int> > g[50005];
int dist[50005];
int n, m;
bool ciclu;


void citire() {
    fin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int a, b, c;
        fin >> a >> b >> c;
        g[a].push_back({b, c});
    }
}



void solve() {
    for(int i = 2; i <= n; i++) dist[i] = 100000000;

    for(int rep = 1; rep < n; rep++)
        for(int i = 1; i <= n; i++) for(int j = 0; j < g[i].size(); j++) {
            int a = i, b = g[i][j].first, c = g[i][j].second;
            if(dist[a]+c < dist[b])
                dist[b] = dist[a]+c;
        }

    for(int i = 1; i <= n; i++) for(int j = 0; j < g[i].size(); j++) {
        int a = i, b = g[i][j].first, c = g[i][j].second;
        if(dist[a]+c < dist[b]) {
            ciclu = true;
            return;
        }
    }

}

void afis() {
    if(ciclu)
        fout << "Ciclu negativ!";
    else
        for(int i = 2; i <= n; i++)
            fout << dist[i] << ' ';
}

int main() {
    citire();
    solve();
    afis();
}