Cod sursa(job #2837668)

Utilizator caracioni_octavianCaracioni Octavian caracioni_octavian Data 22 ianuarie 2022 13:12:13
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

#define NMAX 50005
#define INF 2e9

using namespace std;

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

int n, m;
vector < pair < int, int > > v[NMAX];
vector < int > d;

bool spfa(int start) {
    d.assign(n + 1, INF);

    vector < int > f(n + 1, 0);
    queue < int > q;
    bitset < NMAX > inqueue;

    d[start] = 0;
    q.push(start);
    inqueue[start] = 1;

    while (!q.empty()) {
        int x = q.front();
        q.pop();
        inqueue[x] = 0;

        for (int i = 0; i < v[x].size(); i++) {
            int to = v[x][i].first, w = v[x][i].second;

            if (d[x] + w < d[to]) {
                d[to] = d[x] + w;

                if (!inqueue[to]) {
                    q.push(to);
                    inqueue[to] = 1;
                    f[to]++;

                    if (f[to] >= n)
                        return false;
                }
            }
        }
    }

    return true;
}

int main() {

    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, c;
        fin >> x >> y >> c;

        v[x].push_back(make_pair(y, c));
    }

    if (spfa(1)) {
        for (int i = 2; i <= n; i++)
            fout << d[i] << ' ';
    } else {
        fout << "Ciclu negativ!";
    }

    return 0;
}