Cod sursa(job #2856189)

Utilizator TiberiwTiberiu Amarie Tiberiw Data 23 februarie 2022 15:50:00
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
#define Dmax 50005
#define inf 0x3F3F3F3F
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m,D[Dmax],viz[Dmax];
vector<pair<int,int> >G[Dmax];

void Bellman_Ford(int start)
{
    queue<int> Q;
    for(int i = 1; i<= n; i++)
        D[i] = inf;
    D[start] = 0;
    while(!Q.empty())
    {
        int nod = Q.front();
        Q.pop();
        for(vector<pair<int,int> >::iterator it = G[nod].begin(); it < G[nod].end(); it++)
        {
            int Vecin = it->first;
            int Cost = it->second;
            if(D[Vecin] > D[nod] + Cost)
            {
                D[Vecin] = D[nod] + Cost;
                Q.push(Vecin);
                viz[Vecin]++;
            }
            if(viz[Vecin] > n-1)
            {
                g<<"Ciclu negativ!";
                return ;
            }
        }
    }
    for(int i = 2; i <= n; i++)
    g<<D[i]<<" ";



}

int main()
{
    f>>n>>m;
    for(int i = 1; i <= m; i++)
    {
        int x,y,z;
        f>>x>>y>>z;
        G[x].push_back({y,z});
    }

    Bellman_Ford(1);


    return 0;
}