Cod sursa(job #1318496)

Utilizator blue_skyPetrica Stefan Cosmin blue_sky Data 15 ianuarie 2015 23:59:32
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <list>
#include <queue>
#define DIM 50001
#define INF 999999

using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

int n,m,x,y,c,d[DIM],count[DIM];
list<pair <int,int> > nod[DIM];
queue<int> cd;

void bellmanford(int k)
{
    cd.push(k);
    while(!cd.empty())
    {
        int vf=cd.front();
        for(list<pair <int,int> >::iterator i=nod[vf].begin();i!=nod[vf].end();++i)
        {
            std::pair<int, int> q=*i;
            if(d[vf]+ q.second<d[q.first])
            {
                d[q.first]=d[vf]+ q.second;
                count[q.first]++;
                if(count[q.first] >n)
                {
                    g<<"Ciclu negativ!\n";
                    return;
                }
                cd.push(q.first);
            }
        }
        cd.pop();
    }
    for(int i=2;i<=n;++i)
    g<<d[i]<<" ";
    g<<'\n';
}

int main()
{
    f>>n>>m;
    for(int i=1;i<=m;++i)
    {
        f>>x>>y>>c;
        nod[x].push_back(make_pair(y,c));
    }
    for(int i=2;i<=n;++i)
    d[i]=INF;

    bellmanford(1);
    f.close();
    g.close();
    return 0;
}