Cod sursa(job #3286974)

Utilizator CimpoesuFabianCimpoesu Fabian George CimpoesuFabian Data 14 martie 2025 21:11:54
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

int n, m, viz[50001], cnt[50001], d[50001];
vector<pair<int, int>> G[50001];
priority_queue<pair<int, int>> q;

void Bellman_Ford()
{
    int i;
    for (i = 1 ; i <= n ; i++)
        d[i] = 2e9;
    d[1] = 0;
    q.push({0, 1});
    viz[1] = 1;
    cnt[1] = 1;
    while (!q.empty())
    {
        auto k = q.top().second;
        q.pop();
        for (auto e : G[k])
        {
            i = e.first;
            if (d[i] > d[k] + e.second)
            {
                d[i] = d[k] + e.second;
                if (viz[i] == 0)
                {
                    q.push({-d[i], i});
                    viz[i] = 1;
                    ++cnt[i];
                    if (cnt[i] > n)
                    {
                        fout << "Ciclu negativ!";
                        exit(0);
                    }
                }
            }
        }
    }
}

int main()
{
    int i, x, y, c;
    fin >> n >> m;
    for (i = 1 ; i <= m ; i++)
    {
        fin >> x >> y >> c;
        G[x].push_back({y, c});
    }
    Bellman_Ford();
    for (i = 2 ; i <= n ; i++)
        fout << d[i] << " ";
    return 0;
}