Cod sursa(job #2718279)

Utilizator vlasdumitruVlas Dumitru vlasdumitru Data 8 martie 2021 17:13:45
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 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;
int fv[maxx],bine=1;
void citire(vector <per> G[],int &n, int &m)
{int i,x,y,c;
    fin>>n>>m;
    for (i=1;i<=n;i++)
    {
        fin>>x>>y>>c;
        G[x].push_back(make_pair(y,c));
    }
}
void Bellman (vector <per> G[],int n,int D[],int T[])
{
    bool v[maxx];
    int i,z;
    vector <per>::iterator it;
    for (i=1;i<=n;i++)
    {
        D[i]=pinf;
        T[i]=v[i]=0;
    }
    D[1]=0;
    v[1]=1;
    Q.push(1);
    while (!Q.empty())
    {
        z=Q.front();
        v[z]=0;
        fv[z]++;
        if (fv[z]>=n)
            bine=0;
        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;
                T[it->first]=z;
                if (v[it->first]==0)
                {
                    Q.push(it->first);
                    v[it->first]=1;
                }
            }
        }
        Q.pop();
    }
}
int main()
{int n,m,D[maxx],T[maxx],i;
    vector <per> G[maxx];
    citire(G,n,m);
    Bellman(G,n,D,T);
    if (bine==1)
    for (i=2;i<=n;i++)
        fout<<D[i]<<" ";
    else fout<<"Ciclu negativ!";

    return 0;
}