Cod sursa(job #3271785)

Utilizator THEO0808Teodor Lepadatu THEO0808 Data 27 ianuarie 2025 12:32:17
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>

using namespace std;

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

const int INF = INT_MAX;

bool bellmanFord(int n, int m, vector<vector<pair<int, int>>>& adj, vector<int>& dist, vector<int>& parent) {
    vector<int> vis(n + 1, 0);
    vector<int> negativ(n + 1, 0);
    queue<int> q;

    fill(dist.begin(), dist.end(), INF);
    fill(parent.begin(), parent.end(), -1);

    dist[1] = 0;
    q.push(1);
    vis[1] = 1;

    while (!q.empty()) {
        int from = q.front();
        q.pop();
        vis[from] = 0;

        for (auto [to, w] : adj[from]) {
            if (dist[from] != INF && dist[from] + w < dist[to]) {
                dist[to] = dist[from] + w;
                parent[to] = from;

                if (!vis[to]) {
                    q.push(to);
                    vis[to] = 1;
                }

                negativ[to] = negativ[from] + 1;
                if (negativ[to] > n) {
                    return false;  // Ciclu negativ detectat
                }
            }
        }
    }
    return true;
}

int main() {
    int n, m;
    fin >> n >> m;

    vector<vector<pair<int, int>>> adj(n + 1);
    vector<int> dist(n + 1, INF);
    vector<int> parent(n + 1, -1);

    for (int i = 0; i < m; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        adj[x].push_back({y, c});
    }

    if (bellmanFord(n, m, adj, dist, parent)) {
        for (int i = 2; i <= n; i++) {
            fout << (dist[i] == INF ? 0 : dist[i]) << " ";
        }
    } else {
        fout << "Ciclu negativ!";
    }
}