Cod sursa(job #3138506)

Utilizator hurjui12AlexandruHurjui Alexandru-Mihai hurjui12Alexandru Data 19 iunie 2023 22:17:11
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>
using namespace std;
using llx = long long;

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

const int inf = 1'000'000'000;
vector<vector<pair<int, int>>> v;
vector<int> dist;

bool bellman_ford(int n)
{
    queue<int> q;
    vector<bool> in_queue;
    vector<int> opt;
    int na, x, y;
    dist.assign(n+1, inf), opt.assign(n+1, 0), in_queue.assign(n+1, 0);

    dist[1] = 0;
    q.push(1);
    in_queue[1] = 1;

    while (q.empty() == 0)
    {
        na = q.front();
        q.pop();
        in_queue[na] = 0;

        for (const auto &pairv : v[na])
        {
            tie(x, y) = pairv;
            if (dist[x] > dist[na] + y)
            {
                dist[x] = dist[na] + y;
                if (in_queue[x] == 0)
                {
                    q.push(x);
                    in_queue[x] = 1;

                    opt[x]++;
                    if (opt[x] >= n)
                        return 0;
                }
            }
        }
    }
    return 1;
}

int main()
{
    int n, m, i, x, y, z;

    fin >> n >> m;
    v.resize(n+1);
    for (i = 1; i<=m; i++)
    {
        fin >> x >> y >> z;
        v[x].push_back({y, z});
    }

    if (bellman_ford(n) == 0)
        fout << "Ciclu negativ!";
    else
        for (i = 2; i<=n; i++)
            fout << dist[i] << ' ';
    return 0;
}