Cod sursa(job #3357969)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:24:11
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;

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

const int MAXN = 50001;
const long long INF = 1e18;

int N, M;
vector<pair<int, int>> graph[MAXN];
long long dist[MAXN];
bool inQueue[MAXN];
int cnt[MAXN];

bool bellmanford() {
    queue<int> q;
    for (int i = 1; i <= N; ++i) {
        dist[i] = INF;
        inQueue[i] = false;
        cnt[i] = 0;
    }
    dist[1] = 0;
    q.push(1);
    inQueue[1] = true;

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

        for (auto &edge : graph[node]) {
            int neighbor = edge.first;
            int cost = edge.second;

            if (dist[node] + cost < dist[neighbor]) {
                dist[neighbor] = dist[node] + cost;
                if (!inQueue[neighbor]) {
                    q.push(neighbor);
                    inQueue[neighbor] = true;
                    cnt[neighbor]++;
                    if (cnt[neighbor] >= N) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

int main() {
    fin >> N >> M;
    for (int i = 0; i < M; ++i) {
        int x, y, c;
        fin >> x >> y >> c;
        graph[x].push_back({y, c});
    }

    if (bellmanford()) {
        fout << "Ciclu negativ!";
    } else {
        for (int i = 2; i <= N; ++i) {
            fout << dist[i];
            if (i < N) fout << " ";
        }
    }
    fin.close();
    fout.close();
    return 0;
}