Cod sursa(job #3300790)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 19 iunie 2025 02:16:54
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <cstring>
using namespace std;

const int INF = 0x3f3f3f3f;
const int MAXN = 5e4 + 5;

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

struct Edge {
    int dest, cost;
};

int n, m;
vector<Edge> graph[MAXN];
int relaxCount[MAXN];
int distances[MAXN];
bool inQueue[MAXN];

void ReadData() {
    fin >> n >> m;
    int a, b, c;
    for (int i = 0; i < m; ++i) {
        fin >> a >> b >> c;
        graph[a].push_back({b, c});
    }
}

bool BellmanFord() {
    fill(distances, distances + n + 1, INF);
    memset(relaxCount, 0, sizeof(relaxCount));
    memset(inQueue, 0, sizeof(inQueue));

    queue<int> q;
    distances[1] = 0;
    q.push(1);
    inQueue[1] = true;

    while (!q.empty()) {
        int u = q.front();
        q.pop();
        inQueue[u] = false;

        for (Edge e : graph[u]) {
            if (distances[e.dest] > distances[u] + e.cost) {
                distances[e.dest] = distances[u] + e.cost;
                if (!inQueue[e.dest]) {
                    q.push(e.dest);
                    inQueue[e.dest] = true;
                    relaxCount[e.dest]++;
                    if (relaxCount[e.dest] > n)
                        return false; // Negative cycle
                }
            }
        }
    }
    return true;
}

void Solve() {
    if (!BellmanFord()) {
        fout << "Ciclu!\n";
        return;
    }
    for (int i = 2; i <= n; ++i) {
        fout << distances[i] << ' ';
    }
    fout << '\n';
}

int main() {
    ReadData();
    Solve();
    return 0;
}