Cod sursa(job #2819227)

Utilizator sandifx68Fazakas Alexandru sandifx68 Data 18 decembrie 2021 09:43:17
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
#include <vector>
#include <queue>
#define INF (1<<30-1)

using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int v[50005],dp[50005],n,m;

vector <pair<int,int>>graf[50005];
queue <int>q;

void citire(){
    f>>n>>m;
    for(int i=1;i<=m;i++){
        int x,y,c;
        f>>x>>y>>c;
        graf[x].push_back(make_pair(y,c));
    }
    for(int i=1;i<=n;i++) dp[i]=INF;

}

void bellman(){
    int dmin,k,cost,x,pasi=0;
    dp[1]=0;
    q.push(1);
    v[1]=1;
    while(!q.empty() && pasi<=n-1){
        k=q.front();
        v[k]=0;
        q.pop();
        for(auto&x:graf[k]){
            if(dp[x.first] > dp[k]+x.second){
                dp[x.first]=dp[k]+x.second;
                if(v[x.first]==0){
                    q.push(x.first);
                    v[x.first]=1;
                    pasi++;
                }
            }
        }
    }
}

void afish(){
    for(int i=2;i<=n;i++)
        g<<(dp[i]!=INF?dp[i]:0)<<" ";
}


int main()
{
    citire();
    bellman();
    afish();
}