Cod sursa(job #3184842)

Utilizator xxUnrealUxxNiculae Adrian-Ioan xxUnrealUxx Data 17 decembrie 2023 10:53:11
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>
#define Nmax 500001
#define Mmax 250001
using namespace std;

ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");

int n, m;
vector<pair<int, int>> mat[Nmax];
queue<int>
vector<int> dist(Nmax, 1e9);
int viz[Nmax], cnt[Nmax];


void citire()
{
    cin >> n >> m;

    for(int i = 0, a, b, c; i<m; i++)
    {
        cin >> a >> b >> c;
        mat[a].push_back({b, c});
    }
}

void Bellman_Ford()
{
    for(int i = 1; i<=n; i++)
        dist[i] = 1e9;

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

    while(!q.empty())
    {
        int k = q.front();
        q.pop();
        viz[k] = 0;

        for(auto it : mat[k])
        {
            if(dist[k] + it.second < dist[it.first])
            {
                dist[it.first] = dist[k] + it.second;
                if(!viz[i])
                {
                    viz[i] = 1;
                    q.push(i);
                    cnt[i]++;

                    if(cnt[i] > n)
                    {
                        cout << "Ciclu negativ";
                        exit(0);
                    }
                }
            }
        }
    }

}

void afisare()
{
    for(int i = 2; i<=n; i++)
        cout << dist[i] << ' ';
}

int main()
{

    citire();
    Bellman_Ford()
    afisare();
}