Cod sursa(job #3336344)

Utilizator GridanAntoniaGridan Antonia GridanAntonia Data 24 ianuarie 2026 16:43:47
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

void bellmanford(int v, vector<vector<pair<int, int>>>&adj, bool &cycle, vector<int>&dist, int n)
{
    vector<int>fr(n+1);
    vector<int>tata(n+1);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>pq;

    pq.push({0, v});
    dist[v] = 0;
    while(!pq.empty())
    {
        auto pr = pq.top();
        pq.pop();
        fr[pr.second]++;
        if(fr[pr.second] == n)
        {
            cycle = true;
            return;
        }
        else
        {
            for(auto e : adj[pr.second])
            {
                if(dist[e.first] > dist[pr.second] + e.second)
                {
                    dist[e.first] = dist[pr.second] + e.second;
                    tata[e.first] = pr.second;
                    pq.push({dist[e.first], e.first});
                }
            }
        }
    }
}

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

    vector<vector<pair<int, int>>>adj(n+1);

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

    vector<int>dist(n+1, 1e9+1);
    bool cycle = false;
    bellmanford(1, adj, cycle, dist, n);

    if(cycle == true)
        fout << "Ciclu negativ!";
    else
    {
        for(int i = 2; i <= n; i++)
        {
            if(dist[i] == 1e9+1)
                fout << 0 << " ";
            else
                fout << dist[i] << " ";
        }
    }
    return 0;
}