Cod sursa(job #3275319)

Utilizator witekIani Ispas witek Data 9 februarie 2025 19:10:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int oo = 2e9;
int n, m;
vector <vector<pair<int, int>>> graph;
vector <int> d, cnt;
vector <bool> inQueue;
queue <int> q;

void init() {
    graph = vector<vector<pair<int, int>>> (n + 1);
    d = vector <int> (n + 1, oo);
    cnt = vector <int> (n + 1);
    inQueue = vector <bool> (n + 1);
}

void read() {
    fin >> n >> m;
    init();
    int x, y, dist;
    for(int i = 1; i <= m; i ++) {
        fin >> x >> y >> dist;
        graph[x].push_back({y, dist});
    }
}

bool bellmanford(int startNode) {
    d[startNode] = 0;
    q.push(startNode);
    inQueue[1] = true;
    while(!q.empty()) {
        int node = q.front();
        q.pop();
        if(cnt[node] >= n - 1)
            return false;
        else
            cnt[node] ++;
        inQueue[node] = false;
        for(const auto& neighbour : graph[node]) {
            int otherNode = neighbour.first;
            int otherDist = neighbour.second;
            if(otherDist + d[node] < d[otherNode]) {
                d[otherNode] = otherDist + d[node];
                if(!inQueue[otherNode]) {
                    inQueue[otherNode] = true;
                    q.push(otherNode);
                }
                //q.push(otherNode);
            }
        }
    }
    return true;
}

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