Cod sursa(job #2907882)

Utilizator moltComan Calin molt Data 31 mai 2022 20:11:08
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 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 bellman_ford(int start) {
    d.assign(n + 1, INF);
 
    vector<int> freq(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;
                    freq[to]++;
                    if (freq[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 (bellman_ford(1)) {
        for (int i = 2; i <= n; i++)
            fout << d[i] << " ";
    } else {
        fout << "Ciclu negativ!";
    }
 
    return 0;
}