Cod sursa(job #2029409)

Utilizator cristina_borzaCristina Borza cristina_borza Data 29 septembrie 2017 23:16:07
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;

ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");

const int Inf = 1e9 + 5;
const int Dim = 1e5;

int d[ Dim ], modif[ Dim ];
int n, m, x, y, c;

int fr[ Dim ];

vector <pair <int, int> > G[ Dim ];
queue <int> coada;


void reset () {
    for (int i = 1; i <= n; ++i)
        d[i] = Inf;
}

bool bellman () {
    reset ();
    coada.push (1);

    fr[1] = 1, modif[1] = 1;
    d[1] = 0;

    while (!coada.empty ()) {
        int node = coada.front();
        coada.pop();

        fr[node] = 0;
        for (vector <pair <int, int> > :: iterator it = G[node].begin(); it != G[node].end(); ++it) {
           if (d[it -> first] > d[node] + it -> second) {
                d[it -> first] = d[node] + it -> second;

                if (fr[it -> first] == 0) {
                    ++modif[it -> first];
                    if (modif[it -> first] >= n)
                        return 1;

                    fr[it -> first] = 1;
                    coada.push (it -> first);
                }
            }
        }
    }

    return 0;
}

int main() {
    f >> n >> m;
    for (int i = 1; i <= m; ++i) {
        f >> x >> y >> c;
        G[x].push_back ({y, c});
    }

    if (bellman () == 1) {
        g << "Ciclu negativ!";
    }

    else {
        for (int i = 2; i <= n; ++i) {
            g << d[ i ] << " ";
        }
    }
    return 0;
}