Cod sursa(job #1998176)

Utilizator tanasaradutanasaradu tanasaradu Data 6 iulie 2017 20:45:57
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>
#define nmax 50001
#define oo  LONG_MAX
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n,m,viz[nmax],d[nmax],cnt[nmax];
vector<pair<int,int> >h[nmax];
queue<int>c;
void Citire()
{
    int i,x,y,cost;
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y>>cost;
        h[x].push_back({y,cost});
    }
}
void Bellmanford()
{
    int i,p,q,x;
    bool gata;
    for(i=1; i<=n; i++)
        d[i]=oo;
    d[1]=0;
    c.push(1);
    viz[1]=1;
    gata=true;
    while(!c.empty() && gata)
    {
        x=c.front();
        viz[x]=0;
        c.pop();
        for(i=0; i<h[x].size(); i++)
        {
            p=h[x][i].first;
            q=h[x][i].second;
            if(d[p]>d[x]+q)
            {
                d[p]=d[x]+q;
                if(!viz[p])
                {
                    if(cnt[p]>n)
                        gata=false;
                    else
                    {
                        cnt[p]++;
                        viz[p]=1;
                        c.push(p);
                    }
                }
            }
        }
    }
    if(!gata)
        fout<<"Ciclu negativ\n";
    else
    {
        for(i=2; i<=n; i++)
            fout<<d[i]<<" ";
        fout<<"\n";
    }
}
int main()
{
    Citire();
    Bellmanford();
    fin.close();
    fout.close();
    return 0;
}