Cod sursa(job #3314404)

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

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

void BellmanFord(int nod)
{
    int i, curr;
    for (i = 1 ; i <= n ; i++)
        d[i] = 2e9;
    d[nod] = 0;
    q.push({0, nod});
    ++cnt[nod];
    while (!q.empty())
    {
        int i;
        curr = q.top().second;
        q.pop();
        for (auto next : G[curr])
        {
            i = next.first;
            if (d[i] > d[curr] + next.second)
            {
                d[i] = d[curr] + next.second;
                if (viz[i] == 0)
                {
                    viz[i] = 1;
                    q.push({-d[i], i});
                    ++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});
    }
    BellmanFord(1);
    for (i = 2 ; i <= n ; i++)
        fout << d[i] << " ";
    return 0;
}