Cod sursa(job #3358838)

Utilizator LicaMihaiIonutLica Mihai- Ionut LicaMihaiIonut Data 20 iunie 2026 21:23:56
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include<iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;

int main() {
    ifstream f("bellmanford.in");
    ofstream g("bellmanford.out");
    int n, m;
    f >> n >> m;
    vector<vector<pair<int, int>>> adj(n + 1);
    for (int i = 0; i < m; i++) {
        int x, y, c;
        f >> x >> y >> c;
        adj[x].push_back({y, c});
    }
    vector<long long> dist(n + 1, LLONG_MAX);
    vector<bool> inQ(n + 1, false);
    vector<int> cnt(n + 1, 0);
    queue<int> q;
    dist[1] = 0;
    q.push(1);
    inQ[1] = true;
    bool negCycle = false;
    while (!q.empty() && !negCycle) {
        int u = q.front();
        q.pop();
        inQ[u] = false;
        for (auto& edge : adj[u]) {
            int v = edge.first;
            int w = edge.second;
            if (dist[u] != LLONG_MAX && dist[u] + w < dist[v]) {
                dist[v] = dist[u] + w;
                if (!inQ[v]) {
                    q.push(v);
                    inQ[v] = true;
                    cnt[v]++;
                    if (cnt[v] > n) {
                        negCycle = true;
                        break;
                    }
                }
            }
        }
    }
    if (negCycle) {
        g << "Ciclu negativ!";
    } else {
        for (int i = 2; i <= n; i++) {
            g << dist[i] << ' ';
        }
    }
    f.close();
    g.close();
    return 0;
}