Cod sursa(job #2106906)

Utilizator retrogradLucian Bicsi retrograd Data 16 ianuarie 2018 15:10:44
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>

using namespace std;

const int kMaxN = 50005;
vector<pair<int, int>> G[kMaxN];
long long Dist[kMaxN];
bool In[kMaxN];

void DFS(int node) {
    In[node] = true;
    for (auto e : G[node]) {
        int vec, cost; tie(vec, cost) = e;

        if (Dist[vec] <= Dist[node] + cost) continue;
        
        if (In[vec]) throw 5;
        Dist[vec] = Dist[node] + cost;
        DFS(vec);
    }
    In[node] = false;
}

int main() {
    ifstream cin("bellmanford.in");
    ofstream cout("bellmanford.out");

    int n, m; cin >> n >> m;
    memset(Dist, 0x3f, sizeof(Dist));
    
    while (m--) {
        int a, b, c; cin >> a >> b >> c;
        G[a - 1].emplace_back(b - 1, c);
    }

    Dist[0] = 0;
    try { DFS(0); } catch (int) {
        cout << "Ciclu negativ!" << endl;
        return 0;
    }

    for (int i = 1; i < n; ++i) {
        cout << Dist[i] << " ";
    }
    cout << endl;
    
    return 0;
}