Cod sursa(job #2575765)

Utilizator Fatu_SamuelFatu Samuel Fatu_Samuel Data 6 martie 2020 15:20:08
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 50005;
const int inf = (1 << 30);

int n, m;

struct Point
{
    int to, cost;
};

vector < Point > l[nmax];

queue < int > q;

bitset < nmax > viz;

int cnt[nmax], dist[nmax];

int main()
{
    fin >> n >> m;

    for (int i = 1; i <= m; i++)
    {
        int x, y, c;

        fin >> x >> y >> c;

        l[x].push_back({y, c});
    }

    for (int i = 2; i <= n; i++)
        dist[i] = inf;

    q.push(1);

    cnt[1] = 1;

    viz[1] = 1;


    int nod;

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

        viz[nod] = 0;

        for (Point p : l[nod])
        {
            if (dist[p.to] > dist[nod] + p.cost)
            {
                dist[p.to] = dist[nod] + p.cost;

                if (!viz[p.to])
                {
                    viz[p.to] = 1;
                    cnt[p.to]++;

                    if (cnt[p.to] > n)
                    {
                        fout << "Ciclu negativ!";
                        fin.close();
                        fout.close();
                        return 0;
                    }

                    q.push(p.to);


                }
            }
        }
    }

    for (int i = 2; i <= n; i++)
        fout << dist[i] << ' ';

    fin.close();
    fout.close();
    return 0;
}