Cod sursa(job #2202902)

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

const int inf = 2e9;

struct edge {
    int from, to, weight;
};

vector< edge > Edges;

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) {
            if(dist[edge.from] + edge.weight < dist[edge.to]) {
                dist[edge.to] = dist[edge.from] + edge.weight;
            }
        }
    }

    bool foundNegativCycle = false;
    for(auto edge: Edges) {
            if(dist[edge.from] + edge.weight < dist[edge.to]) {
                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;

    Edges.resize(m);

    for(int i = 0; i < m; ++i) {
        in >> Edges[i].from >> Edges[i].to >> Edges[i].weight;
    }

    Bellman_Ford(n);

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