Cod sursa(job #3324944)

Utilizator petru-robuRobu Petru petru-robu Data 24 noiembrie 2025 11:07:27
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

const ll inf = 1000000000;

string message = "Ciclu negativ!\n";
int n, m;
vector<vector<pair<int, int>>> adj_list;

vector<int> d, cnt, in_queue;

void read()
{
    fin >> n >> m;

    adj_list.assign(n+1, {});
    d.assign(n+1, inf);
    cnt.assign(n+1, 0);
    in_queue.assign(n+1, 0);

    for(int i=0; i<m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;

        adj_list[x].push_back({y, c});
    }
}

void spfa()
{
    queue<int> q;

    d[1] = 0;
    in_queue[1] = 1;

    q.push(1);
    while(!q.empty())
    {
        int v = q.front();
        q.pop();
        in_queue[v] = 0;

        for(auto &edge:adj_list[v])
        {
            int to = edge.first;
            int len = edge.second;

            if(d[v] + len < d[to])
            {
                d[to] = d[v] + len;
                if(!in_queue[to])
                {
                    q.push(to);
                    in_queue[to] = 1;
                    cnt[to] ++;

                    if(cnt[to] > n)
                    {
                        fout<<message;
                        return;
                    }
                }
            }
        }
    }

    for(int i=2; i<=n; i++)
        fout<<d[i]<<' ';
}


int main()
{
    read();
    spfa();
    return 0;
}