Cod sursa(job #2202915)

Utilizator TooHappyMarchitan Teodor TooHappy Data 10 mai 2018 13:23:38
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 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] != inf && 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] != inf && dist[edge.from] + edge.weight < dist[edge.to]) {
            foundNegativCycle = true;
            break;
        }
    }

    if(foundNegativCycle) {
        out << "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;
        Edges[i].from--;
        Edges[i].to--;
    }

    Bellman_Ford(n);

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