Cod sursa(job #2575868)

Utilizator tudormoldovan1Tudor Moldovan tudormoldovan1 Data 6 martie 2020 15:54:53
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda imded Marime 1.09 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<vector<pair<int,int>>>G;
int n,m,D[50005],C[50005];
const int INF=0x3f3f3f3f;
bool ciclu;
void BF()
{
    for(int i=2;i<=n;++i)
        D[i]=INF;
    queue<int>Q;
    Q.push(1);
    while(!Q.empty())
    {
        int x=Q.front();
        ++C[x];
        if(C[x]==n)
        {
            ciclu=true;
            return;
        }
        Q.pop();
        for(auto p : G[x])
        {
            int y = p.second;
            int w = p.first;
            if(D[y]>D[x]+w)
            {
                D[y]=D[x]+w;
                Q.push(y);
            }
        }
    }
}
int main()
{
    fin>>n>>m;
    G.resize(n+1);
    for(int i=1;i<=m;++i)
    {
        int x,y,w;
        fin>>x>>y>>w;
        G[x].push_back({w,y});
    }
    BF();
    if(ciclu)
    {
        fout<<"Ciclu negativ!";
    }
    else
    {
        for(int i=2;i<=n;++i)
            fout<<D[i]<<" ";
    }
    return 0;
}