Cod sursa(job #2353998)

Utilizator nurof3nCioc Alex-Andrei nurof3n Data 24 februarie 2019 19:39:13
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
//SHORTEST PATH FASTER ALGORITHM = DIJKSTRA CU COADA SIMPLA


#include <fstream>
#include <vector>

using namespace std;

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

const int MAX = 50001;

int Q[MAX * 4], cnt_inQ[MAX];
int st, dr;
vector<pair<int, int>> G[MAX];

int D[MAX];  //retine costul minim al drumului pana la fiecare nod, care trece doar prin nodurile vizitate
int N, M;
bool inQ[MAX];

bool SPFA() {
    int i, vf, nod, cost, lg;
    bool not_ok = false;
    while (st <= dr && !not_ok) {
        vf = Q[st++];
        inQ[vf] = false;
        lg = G[vf].size();
        for (i = 0; i < lg; i++) {
            nod = G[vf][i].first;
            cost = G[vf][i].second;
            if (D[vf] + cost < D[nod]) {
                D[nod] = D[vf] + cost;
                if(!inQ[nod])
                    if(cnt_inQ[nod] > N)    //avem circuit negativ
                        not_ok = true;
                    else {
                        Q[++dr] = nod;
                        inQ[nod] = true;
                        ++cnt_inQ[nod];
                    }

            }
        }
    }
    return not_ok;
}

int main() {

    int x, y, cost;
    in >> N >> M;
    for (int i = 1; i <= N; i++)
        D[i] = 1000000;
    D[1] = 0;

    st = 1, dr = 0;
    for (int i = 1; i <= M; i++) {
        in >> x >> y >> cost;
        G[x].push_back (pair<int, int> (y, cost));
        if(x == 1) {
            D[y] = cost;
            Q[++dr] = y;
            inQ[y] = true;
        }
    }

    if(SPFA()) {
        out << "Ciclu negativ!";
        return 0;
    }

    for (int i = 2; i <= N; i++)
        if (D[i] < 1000000)
            out << D[i] << ' ';
        else
            out << 0 << ' ';

    return 0;
}