Cod sursa(job #3275318)

Utilizator witekIani Ispas witek Data 9 februarie 2025 19:06:44
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 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;
queue <int> q;

void init() {
    graph = vector<vector<pair<int, int>>> (n + 1);
    d = vector <int> (n + 1, oo);
    cnt = vector <int> (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);
    while(!q.empty()) {
        int node = q.front();
        q.pop();
        if(cnt[node] >= n - 1)
            return false;
        else
            cnt[node] ++;
        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];
                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!";
}