Cod sursa(job #3237166)

Utilizator Sasha_12454Eric Paturan Sasha_12454 Data 5 iulie 2024 20:29:03
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

std :: ifstream in ("bellmanford.in");

std :: ofstream out ("bellmanford.out");

const int NMAX = 5e4 + 5;

const int INF = 2e9;

int n;

int m;

int x;

int y;

int d;

int dist[NMAX];

int cnt[NMAX];

bool inq[NMAX];

std :: vector <std :: pair <int, int>> v[NMAX];

std :: queue <int> q;

int main()
{

    in >> n >> m;

    for(int i = 1; i <= m; i ++)
    {
        in >> x >> y >> d;

        v[x].push_back(std :: make_pair(y, d));
    }

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

    dist[1] = 0;

    q.push(1);

    inq[1] = true;

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

        q.pop();

        if(cnt[nod] >= n)
        {
            out << "Ciclu negativ!";
            return 0;
        }

        inq[nod] = false;

        for(auto i : v[nod])
        {
            if(dist[nod] + i.second < dist[i.first])
            {
                dist[i.first] = dist[nod] + i.second;

                cnt[i.first] ++;

                if(inq[i.first] == false)
                {
                    inq[i.first] = true;

                    q.push(i.first);
                }
            }
        }
    }

    for(int i = 2; i <= n; i ++)
    {
        out << dist[i] << " ";
    }

    return 0;
}