Cod sursa(job #3216238)

Utilizator robert_dumitruDumitru Robert Ionut robert_dumitru Data 15 martie 2024 19:00:52
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m;
int d[50005], viz[50005], cnt[50005];
vector<pair<int, int>> L[50005];
queue<int> q;

void Bellman_Ford()
{
    for (int i = 1; i <= n; i++)
        d[i] = 2e9;
    d[1] = 0;
    cnt[1] = viz[1] = 1;
    q.push(1);
    while (!q.empty())
    {
        int k = q.front();
        q.pop();
        viz[k] = 1;
        for (auto i : L[k])
            if (d[i.first] > d[k] + i.second)
            {
                d[i.first] = d[k] + i.second;
                if (viz[i.first] == 0)
                {
                    viz[i.first] = 1;
                    cnt[i.first]++;
                    if (cnt[i.first] > n)
                    {
                        fout << "Ciclu negativ!";
                        exit(0);
                    }
                    q.push(i.first);
                }
            }
    }
}

int main()
{
    int i, j, c;
    fin >> n >> m;
    while (m--)
    {
        fin >> i >> j >> c;
        L[i].push_back({j, c});
    }
    Bellman_Ford();
    for (i = 2; i <= n; i++)
        fout << d[i] << " ";
    return 0;
}