Cod sursa(job #2896965)

Utilizator mihnea.tTudor Mihnea mihnea.t Data 1 mai 2022 18:46:45
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>

#define INF ((int)1e9)
#define NMAX ((int)5e4)

using namespace std;

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

struct edge {
    int dest, cost;
};

int n, m;
vector<edge> a[NMAX + 1];
int dist[NMAX + 1];
int pred[NMAX + 1];
bool in_queue[NMAX + 1];
int cnt_in_queue[NMAX + 1];

bool bellmanford() {
    for (int i = 1; i <= n; ++i) {
        dist[i] = INF;
        pred[i] = -1;
    }

    dist[1] = 0;

    queue<int> q;

    q.push(1);
    in_queue[1] = true;

    while (!q.empty()) {
        int node = q.front();
        q.pop();
        in_queue[node] = false;

        for (auto it = a[node].begin(); it != a[node].end(); ++it) {
            if (dist[node] < INF) {
                edge next = *it;
                if (dist[next.dest] > dist[node] + next.cost) {
                    dist[next.dest] = dist[node] + next.cost;

                    if (!in_queue[next.dest]) {
                        if (cnt_in_queue[next.dest] > n) {
                            return false;
                        } else {
                            q.push(next.dest);
                            in_queue[next.dest] = true;
                            ++cnt_in_queue[next.dest];
                        }
                    }
                }
            }
        }
    }

    return true;
}

int main(void) {
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        int src, dest, cost;
        fin >> src >> dest >> cost;

        a[src].push_back({dest, cost});
    }
    
    if (!bellmanford()) {
        fout << "Ciclu negativ!\n";
        return 0;
    }

    for (int i = 2; i <= n; ++i) {
        fout << dist[i] << " ";
    }

    fout << "\n";

    return 0;
}