Cod sursa(job #3239400)

Utilizator GabrielPopescu21Silitra Gabriel - Ilie GabrielPopescu21 Data 5 august 2024 14:08:06
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;

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

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

    while (!q.empty())
    {
        int node = q.front();
        q.pop();

        for (pair<int,int> next : graph[node])
        {
            if (dist[next.first] > dist[node] + next.second)
            {
                dist[next.first] = dist[node] + next.second;
                q.push(next.first);

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

    return 1;
}

int main()
{
    ifstream cin("bellmanford.in");
    ofstream cout("bellmanford.out");
    cin >> n >> m;
    dist.assign(n+1, LLONG_MAX);
    cnt.assign(n+1, 0);

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

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

    return 0;
}