Cod sursa(job #2176386)

Utilizator nicu_serteSerte Nicu nicu_serte Data 17 martie 2018 00:49:41
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
#define nmax 50005
#define inf (INT_MAX-1)
vector<pair<int, int> > g[nmax];
queue<int> q;
int n, m, frQ[nmax], cNeg=0, dst[nmax];
bool inQ[nmax];
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));
    }
    fin.close();
}
void BellmanFord()
{
    int i, k;
    vector<pair<int, int>>::iterator it;
    for(i=1; i<=n; i++)
        dst[i]=inf;
    dst[1]=0;
    frQ[1]=1;
    inQ[1]=1;
    q.push(1);
    while(!cNeg && !q.empty())
    {
        k=q.front();
        q.pop();
        inQ[k]=0;
        for(it=g[k].begin(); it!=g[k].end(); it++)
            if(dst[k]<inf && dst[it->first]>dst[k]+it->second)
            {
                dst[it->first]=dst[k]+it->second;
                if(!inQ[it->first])
                {
                    inQ[it->first]=1;
                    frQ[it->first]++;
                    q.push(it->first);
                    if(frQ[it->first]>n)
                        cNeg=1;
                }
            }
    }
}
void afisare()
{
    if(cNeg)
        fout<<"Ciclu negativ!";
    else for(int i=2; i<=n; i++)
        fout<<dst[i]<<' ';
    fout<<'\n';
    fout.close();
}
int main()
{
    citire();
    BellmanFord();
    afisare();
    return 0;
}