Cod sursa(job #2968128)

Utilizator Matei_MunteanuMunteanu Matei Ioan Matei_Munteanu Data 20 ianuarie 2023 18:38:52
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;
const int NMAX = 50004;
const int INF = 100000000;

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

int n, m;
vector<pair<int, int>> adj[NMAX];
queue<int> Q;
vector<int> d;
vector<bool> in_queue;
vector<int> cnt;

bool sfpa()
{
    d.assign(n + 1, INF);
    cnt.assign(n + 1, 0);
    in_queue.assign(n + 1, false);
    d[1] = 0;
    Q.push(1);
    in_queue[1] = true;
    while (!Q.empty())
    {
        int v = Q.front();
        Q.pop();
        in_queue[v] = false;
        for (auto edge : adj[v])
        {
            int u = edge.first;
            int cost = edge.second;
            if (d[v] + cost < d[u])
            {
                d[u] = d[v] + cost;
                if (!in_queue[u])
                {
                    Q.push(u);
                    in_queue[u] = true;
                    cnt[u]++;
                    if (cnt[u] > n)
                    {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        fin >> a >> b >> c;
        adj[a].push_back({b, c});
    }
    bool ok = sfpa();
    if (ok)
    {
        for (int i = 2; i <= n; i++)
        {
            fout << d[i] << ' ';
        }
    }
    else
    {
        fout << "Ciclu negativ!";
    }
    return 0;
}