Cod sursa(job #2721893)

Utilizator danhHarangus Dan danh Data 12 martie 2021 13:38:15
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

const int NMAX = 50005;
const int inf = (1LL<<31) - 1;

queue<int> q;
vector<pair<int, int> > v[NMAX];

int dist[NMAX];
int cnt[NMAX];
bitset<NMAX> in_q;

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

    fin>>n>>m;

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

    for(i=1; i<=n; i++)
    {
        dist[i] = inf;
    }

    q.push(1);
    dist[1] = 0;
    in_q[1] = 1;
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        in_q[x] = 0;
        for(pair<int, int> e : v[x])
        {
            int nod = e.first;
            int cost = e.second;
            if(dist[nod] > dist[x] + cost)
            {
                dist[nod] = dist[x] + cost;
                if(!in_q[nod])
                {
                    cnt[nod]++;
                    if(cnt[nod] > n)
                    {
                        fout<<"Ciclu negativ!";
                        fin.close();
                        fout.close();
                        return 0;
                    }
                    in_q[nod] = 1;
                    q.push(nod);

                }
            }
        }
    }

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

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