Cod sursa(job #2927150)

Utilizator C_R_I_S_T_I_2_3Cristi Gavrila C_R_I_S_T_I_2_3 Data 19 octombrie 2022 18:02:40
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>
#define MAX 999999999
using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct muchie
{
    int nod, cost;
};
queue <int> q;
vector <muchie> v[50005];
int n, m;
bool negativ = 0;
bool viz[50005];
int dp[50005], fr[50005];

inline void Citire()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i ++)
    {
        int a;
        muchie aux;
        fin >> a >> aux.nod >> aux.cost;
        v[a].push_back(aux);
    }
}
inline void BellmanFord(int start)
{
    for(int i = 1; i <= n; i ++)
    {
        dp[i] = MAX;
    }
    dp[start] = 0;
    fr[start] = 1;
    viz[start] = 1;
    q.push(start);
    while(!q.empty() && !negativ)
    {
        int aux = q.front();
        q.pop();
        viz[aux] = 0;
        for(auto it: v[aux])
        {
            if(dp[it.nod] > dp[aux] + it.cost)
            {
                dp[it.nod] = dp[aux] + it.cost;
                if(viz[it.nod] == 0)
                {
                    viz[it.nod] = 1;
                    q.push(it.nod);
                    fr[it.nod] ++;
                    if(fr[it.nod] > n)
                        negativ = 1;
                }
            }
        }
    }
}
int main()
{
    Citire();
    BellmanFord(1);
    if(negativ)
    {
        fout << "Ciclu negativ!";
    }
    else
    {
        for(int i = 2; i <= n; i ++)
        {
            fout << dp[i] << " ";
        }
    }
    return 0;
}