Cod sursa(job #2718316)

Utilizator vlasdumitruVlas Dumitru vlasdumitru Data 8 martie 2021 17:38:57
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int maxx=50001;
const int pinf=1<<29;
typedef pair < int,int > per;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
queue <int> Q;
vector <per> G[maxx];
int fv[maxx],bine=1,n,m,D[maxx],v[maxx];
void citire()
{
    int i,x,y,c;
    fin>>n>>m;
    for (i=1; i<=m; i++)
    {
        fin>>x>>y>>c;
        G[x].push_back(make_pair(y,c));
    }
}
void Bellman ()
{
    int i,z;
    vector <per>::iterator it;
    for (i=1; i<=n; i++)
    {
        D[i]=pinf;
        v[i]=0;
    }
    D[1]=0;
    v[1]=1;
    Q.push(1);
    while (!Q.empty())
    {
        z=Q.front();
        Q.pop();
        v[z]=0;
        fv[z]++;
        if (fv[z]>n)
        {
            bine=0;
            return;
        }
        for (it=G[z].begin(); it!=G[z].end(); it++)
        {
            if (D[z]+it->second<D[it->first])
            {
                D[it->first]=D[z]+it->second;
                if (v[it->first]==0)
                {
                    Q.push(it->first);
                    v[it->first]=1;
                }
            }
        }
    }
}
int main()
{
    int i;
    citire();
    Bellman();
    if (bine==1)
    {
        for (i=2; i<=n; i++)
            fout<<D[i]<<" ";
    }
    else fout<<"Ciclu negativ!";

    return 0;
}