Cod sursa(job #3344435)

Utilizator GabrielPopescu21Silitra Gabriel - Ilie GabrielPopescu21 Data 1 martie 2026 23:14:47
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
using namespace std;

const int MAX = 50005;
vector<pair<int,int>> graph[MAX];
vector<int> dist, visited, cnt;
int n, m;

int bellmanford()
{
    queue<int> q;
    q.push(1);
    dist[1] = 0;
    cnt[1] = 1;
    visited[1] = 1;

    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        visited[node] = 0;

        for (auto next : graph[node])
            if (dist[next.first] > dist[node] + next.second)
            {
                dist[next.first] = dist[node] + next.second;
                if (!visited[next.first])
                {
                    q.push(next.first);
                    ++cnt[next.first];

                    if (cnt[next.first] > n)
                        return 0;
                }
            }
    }

    return 1;
}

int main()
{
    ifstream fin("bellmanford.in");
    ofstream fout("bellmanford.out");
    fin >> n >> m;
    dist.assign(n+1, INT_MAX);
    visited.assign(n+1, 0);
    cnt.assign(n+1, 0);

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

    if (bellmanford())
        for (int i = 2; i <= n; ++i)
            fout << dist[i] << " ";
    else
        fout << "Ciclu negativ!";

    return 0;
}