Cod sursa(job #2202895)

Utilizator TooHappyMarchitan Teodor TooHappy Data 10 mai 2018 12:43:08
Problema Algoritmul Bellman-Ford Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
using namespace std;
     
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

const int MMax = 25e4;
const int inf = 2e9;

vector< pair< int, pair< int, int > > > Edges(MMax);

void Bellman_Ford(int n) {
    vector< int > dist(n, inf);

    dist[0] = 0;

    for(int i = 1; i <= n - 1; ++i) {
        for(auto edge: Edges) {
            int from = edge.first;
            int to = edge.second.first;
            int weight = edge.second.second;

            if(dist[from] + weight < dist[to]) {
                dist[to] = dist[from] + weight;
            }
        }
    }

    bool foundNegativCycle = false;
    for(auto edge: Edges) {
        int from = edge.first;
        int to = edge.second.first;
        int weight = edge.second.second;

        if(dist[from] + weight < dist[to]) {
            bool foundNegativCycle = true;
            break;
        }        
    }

    if(foundNegativCycle) {
        cout << "Ciclu negativ!\n";
    } else {
        for(int i = 1; i < n; ++i) {
            out << dist[i] << " ";
        }
    }
}

int main() {
    ios::sync_with_stdio(false); in.tie(0); out.tie(0);

    int n, m; in >> n >> m;

    for(int i = 1; i <= m; ++i) {
        int x, y, c; in >> x >> y >> c;

        Edges.push_back({x - 1, {y - 1, c}});
    }

    Bellman_Ford(n);

    in.close(); out.close();
     
    return 0;
}