Cod sursa(job #2321249)

Utilizator andra_moldovanAndra Moldovan andra_moldovan Data 15 ianuarie 2019 21:08:37
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>

#define inf 0x3f3f3f3f
#define MAXN 50005

using namespace std;

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

struct two{
    int node, c;
};

int cost[MAXN], contor[MAXN];
queue <two> Q;
vector <two> graph[MAXN];

inline void Read(int &N, int &M) {
    int x, y, z;

    fin >> N >> M;

    for (int i = 1; i <= M; i++) {
        fin >> x >> y >> z;

        graph[x].push_back({y, z});
        //graph[y].push_back({x, z});
    }
}

inline int BellmanFord(int N, int node) {
    two z;

    memset(cost, inf, sizeof(cost));
    cost[node] = 0;
    Q.push({node, cost[node]});

    while (!Q.empty()) {
        z = Q.front();
        Q.pop();

        if (contor[z.node] > N - 1)
            return 0;

        for (auto x : graph[z.node]) {
            if (cost[x.node] > cost[z.node] + x.c) {
                cost[x.node] = cost[z.node] + x.c;
                contor[x.node]++;
                Q.push({x.node, cost[x.node]});
            }
        }
    }

    return 1;
}

int main () {
    int N, M;
    Read(N, M);
    int ok = BellmanFord(N, 1);

    if (ok) {
        for (int i = 2; i <= N; i++)
            fout << cost[i] << " ";
    }
    else
        fout << "Ciclu negativ!" << "\n";

    fin.close(); fout.close(); return 0;
}