Cod sursa(job #2981343)

Utilizator TheLostRevolverCalin Andrei TheLostRevolver Data 17 februarie 2023 19:40:54
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;
const int nMax = 50001;

vector<pair<int, int>> v[nMax];
int dist[nMax];

bool bellmanford(const int &nodStart, const int nrNoduri, const int nrMuchii) {
    for (int i = 2; i <= nrNoduri; i++)
        dist[i] = INT_MAX;

    queue<int> q;
    q.push(nodStart);
    long long co = 0;
    while (!q.empty()) {
        const int nodCurent = q.front();
        q.pop();

        co++;
        if (1LL * co >= 1LL * nrNoduri * nrMuchii)
            return false;

        for (auto &[vecin, cost]: v[nodCurent]) {
            if (dist[nodCurent] + cost < dist[vecin]) {
                dist[vecin] = dist[nodCurent] + cost;
                q.push(vecin);
            }
        }
    }

    return true;
}

int main() {
    ifstream fin("bellmanford.in");
    ofstream fout("bellmanford.out");
    int n, m;

    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int a, b, cost;
        fin >> a >> b >> cost;
        v[a].emplace_back(b, cost);
    }

    if (bellmanford(1, n, m)) {
        for (int i = 2; i <= n; i++)
            fout << dist[i] << ' ';
    } else {
        fout << "Ciclu negativ!\n";
    }

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