Cod sursa(job #3261479)

Utilizator Barbu_MateiBarbu Matei Barbu_Matei Data 6 decembrie 2024 11:41:26
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
using namespace std;

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

struct nod {
    int node, cost;
};

class comp {
public:
    bool operator()(nod a, nod b) {
        return a.cost > b.cost;
    }
};

bool bellman(int start) {
    memset(cost, 0x3f, sizeof(cost));
    priority_queue<nod, vector<nod>, comp> q;
    q.push({start, 0});
    cost[start] = 0;
    while (!q.empty()) {
        int node = q.top().node;
        q.pop();
        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;
                ++vis[v[node][i].first];
                q.push({v[node][i].first, cost[v[node][i].first]});
            }
        }
    }
    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!";
    }
}