Cod sursa(job #2376320)

Utilizator iarinatudorTudor Iarina Maria iarinatudor Data 8 martie 2019 14:51:48
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <climits>
#include <queue>

using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n,m;
vector <pair <int,int> >G[50010];
queue <int>Q;
int dp[50010],ok[50010],cnt[50010];
void citire()
{
    fin>>n>>m;
    int x,y,c;
    for(int i=1; i<=m; i++)
    {
        fin>>x>>y>>c;
        G[x].push_back({y,c});
    }
    for(int i=2; i<=n; i++)
        dp[i]=INT_MAX/2;
}
bool neg;
void bellmanford()
{
    ok[1]=1;
    Q.push(1);
    cnt[1]++;
    while(!Q.empty()&&neg==0)
    {
        int x=Q.front();
        ok[x]=0;
        Q.pop();
        for(auto v:G[x])
        {   int cost=v.second;
            int y=v.first;
            if(dp[y]>dp[x]+cost)
            {
                dp[y]=dp[x]+cost;
                if(!ok[y])
                {
                    ok[y]=1;
                    Q.push(y);
                    cnt[y]++;
                    if(cnt[y]>n)
                    {
                        neg=1;
                    }
                }
            }
        }
    }
}
int main()
{
    citire();
    bellmanford();
    if(neg==0)
    for(int i=2; i<=n; i++)
        fout<<dp[i]<<" ";
    else
        fout<<0<<" ";
    return 0;
}