Cod sursa(job #2583149)

Utilizator PetrescuAlexandru Petrescu Petrescu Data 17 martie 2020 20:23:14
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
#define MAX 50000 + 5
#define INF 2e9

using namespace std;

vector<pair<int, int>>graph[MAX];
int dist[MAX], vf[MAX];
int main()
{
    ifstream fin("bellmanford.in");
    ofstream fout("bellmanford.out");

    ios::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);
    srand(time(NULL));

    int n, m;

    fin >> n >> m;

    for(int i = 1; i <= n; i++)
    {
        int a, b, cost;

        fin >> a >> b >> cost;

        graph[a].push_back({b, cost});
    }

    queue<pair<int, int>>Q;
    bool eCiclu = false;

    dist[1] = 0;
    for(int i = 2; i <= n; i++)dist[i] = INF;

    Q.push({1, 0});

    while(!eCiclu && Q.size())
    {
        int nod = Q.front().first;
        int distCurrent = Q.front().second;

        Q.pop();

        for(auto vecin : graph[nod])
        {
            if(dist[vecin.first] > distCurrent + vecin.second)
            {
                dist[vecin.first] = distCurrent + vecin.second;
                vf[vecin.first]++;
                Q.push({vecin.first, vecin.second});

                if(vf[vecin.first] == n)
                    eCiclu = true;
            }
        }
    }

    if(eCiclu)fout << "Ciclu negativ!";
    else
        for(int i = 2; i <= n; i++)fout << dist[i] << " ";

    fin.close();
    fout.close();

    return 0;
}