Cod sursa(job #3266849)

Utilizator iccjocIoan CHELARU iccjoc Data 10 ianuarie 2025 17:40:11
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>
using namespace std;
vector<int> bellman(int n, vector<int> sources, vector<vector<pair<int, int>>> graph)
{
    const int INF = 2e9;
    queue<int> q;
    vector<int> dist(n + 1, INF);
    vector<int> nrnd(n + 1, 0);
    for(auto it = sources.begin(); it != sources.end(); it++)
    {
        q.push((*it));
        dist[(*it)] = 0;
        nrnd[(*it)] = 1;
    }
    while(!q.empty())
    {
        int nd = q.front();
        q.pop();
        if(nrnd[nd] > n)
            return vector<int>(1, -1);
        for(auto it = graph[nd].begin(); it != graph[nd].end(); it++)
        {
            if(dist[(*it).first] > dist[nd] + (*it).second)
            {
                dist[(*it).first] = dist[nd] + (*it).second;
                nrnd[(*it).first] = nrnd[nd] + 1;
                q.push((*it).first);
            }
        }
    }
    return dist;
}
int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    vector<vector<pair<int, int>>> graph(n + 1);
    for(int i = 0; i < m; i++)
    {
        int x, y, c;
        cin >> x >> y >> c;
        graph[x].push_back({y, c});
    }
    vector<int> dist;
    dist = bellman(n, vector<int>(1, 1), graph);
    if(dist.size() == 1)
        cout << "Ciclu negativ!";
    else
    {
        for(auto it = dist.begin() + 2; it != dist.end(); it++)
        {
            cout << (*it) << " ";
        }
    }
}