Cod sursa(job #2831678)

Utilizator Teodor_AxinteAxinte Teodor-Ionut Teodor_Axinte Data 11 ianuarie 2022 21:15:22
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

const int N = 500010;
const int oo = 200000010;

int intrari[N], cost[N];
vector<pair<int,int>> adj[N];
queue<int> q;

int n,m;

void bellman()
{
    q.push(1);
    cost[1]=0;
    intrari[1] = 1;
    while(!q.empty())
    {
        int nod_curent = q.front();
        int cost_curent = cost[nod_curent];

        q.pop();

        for(auto it : adj[nod_curent])
        {
            int vecin = it.first;
            int cost_vecin = it.second;

            if(cost[vecin] > cost_curent + cost_vecin)
            {
                cost[vecin] = cost_curent + cost_vecin;
                q.push(vecin);
                intrari[vecin] ++ ;
                if(intrari[vecin] >= n)
                {
                    fout<<"Ciclu negativ";
                    return;
                }
            }
        }
    }
}

int main()
{
    fin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,cost;
        adj[x].push_back({y,cost});
    }

    for(int i=1;i<=n;i++)
    cost[i] = oo;

    bellman();

    for(int i=2;i<=n;i++)
        if(cost[i] == oo)
            fout<<"0 ";
        else
            fout<<cost[i]<<" ";

    return 0;

}