Cod sursa(job #3262325)

Utilizator Barbu_MateiBarbu Matei Barbu_Matei Data 9 decembrie 2024 18:47:34
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>
using namespace std;

int n, m;
vector<pair<int, int>> v[50001];
int cost[50001], vis[50001], inq[50001];

bool bellman(int start) {
    memset(cost, 0x3f, sizeof(cost));
    queue<int> q;
    q.push(start);
    cost[start] = 0;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        ++vis[node];
        if (vis[node] >= n) {
            return false;
        }
        for (int i = 0; i < v[node].size(); ++i) {
            if (cost[node] + v[node][i].second < cost[v[node][i].first]) {
                cost[v[node][i].first] = cost[node] + v[node][i].second;
                if (!inq[v[node][i].first]) {
                    inq[v[node][i].first] = 1;
                    q.push(v[node][i].first);
                }
            }
        }
        inq[node] = 0;
    }
    return true;
}

int main() {
    ifstream cin("bellmanford.in");
    ofstream cout("bellmanford.out");
    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y, c;
        cin >> x >> y >> c;
        v[x].push_back({y, c});
    }
    if (bellman(1)) {
        for (int i = 2; i <= n; ++i) {
            cout << cost[i] << " ";
        }
    } else {
        cout << "Ciclu negativ!";
    }
}