Cod sursa(job #2589074)

Utilizator k2e0e0w3qDumitrescu Gheorghe k2e0e0w3q Data 25 martie 2020 19:09:55
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>
#define N 50001
#define INF 0x3F3F3F3F
using namespace std;

bitset <N> enqueue;
vector <pair <int, int>> G[N];
array <int, N> dist, ct;
class cmp {
public:
    bool operator () (const int &a, const int &b) {
        return dist[a]>dist[b];
    }
};

int main () {
    ifstream fin ("bellmanford.in");
    ofstream fout ("bellmanford.out");
    ios::sync_with_stdio(false);

    int n, m, i, j, c;
    fin >> n >> m;
    for (; m; m--) {
        fin >> i >> j >> c;
        G[i].push_back(make_pair(j, c));
    }

    dist.fill(INF);
    priority_queue <int, vector <int>, cmp> Q;
    Q.push(1);
    enqueue[1]=ct[1]=1;
    dist[1]=0;
    while (!Q.empty()) {
        auto save=Q.top();
        Q.pop();
        enqueue[save]=0;

        for (auto it: G[save])
            if (dist[it.first]>dist[save]+it.second) {
                dist[it.first]=dist[save]+it.second;
                Q.push(it.first);
                enqueue[it.first]=1;
                ct[it.first]++;
                if (ct[it.first]==n) {
                    fout << "Ciclu negativ!";
                    return 0;
                }
            }
    }
    for (i=2; i<=n; i++)
        fout << dist[i] << ' ';
    return 0;
}