Cod sursa(job #1378047)

Utilizator maribMarilena Bescuca marib Data 6 martie 2015 10:17:21
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 2.28 kb
#include <fstream>
#include <vector>
#include <set>
#define DIM 50001
#define INF 0x3f3f3f3f
using namespace std;

ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

struct muchie
{
    short price; int dest;
};

muchie temp;

vector <muchie> node[DIM];

struct stare
{
    int place, way;
};

struct classcomp
{
    bool operator () (const stare &A, const stare &B) const
    {
        if(A.way!=B.way)
            return A.way<B.way;
        else return A.place<B.place;
    }
};

set <stare, classcomp> bf;

set <stare, classcomp> :: iterator it;

stare temp1, temp2;

int n, m, best[DIM];

void bellmanford()
{
    int step=0, vfc, drum;
    temp1.place=1; temp1.way=0;
    best[1]=0;
    bf.insert(temp1);
    while(step<(long long)n*m&&bf.size())
    {
        it=bf.begin();
        temp1=*it;
        bf.erase(it);
        step++;
        vfc=temp1.place;
        drum=temp1.way;
        for(int i=0; i<node[vfc].size(); ++i)
        {
            temp=node[vfc][i];
            if(temp.price+drum<best[temp.dest])
            {
                temp2.place=temp.dest;
                temp2.way=best[temp.dest];
                it=bf.find(temp2);
                if(it!=bf.end())
                    bf.erase(it);
                temp2.way=temp.price+drum;
                best[temp.dest]=temp2.way;
                bf.insert(temp2);
            }
        }
    }
}

void initialize()
{
    for(int i=2; i<=n; ++i)
    {
        best[i]=INF;
    }
}

int check()
{
    for(int i=1; i<=n; ++i)
    {
        for(int j=0; j<node[i].size(); ++j)
        {
            temp=node[i][j];
            if(temp.price+best[i]<best[temp.dest])
            {
                return 1;
                goto p;
            }
        }
    }
    return 0;
    p: ;
}

int main()
{
    in>>n>>m;
    for(int i=1; i<=m; ++i)
    {
        int x, y, cost;
        in>>x>>y>>cost;
        temp.price=cost;
        temp.dest=y;
        node[x].push_back(temp);
    }
    initialize();
    bellmanford();
    if(check())
    {
        out<<"-1\n";
    }
    else
    {
        for(int i=2; i<=n; ++i)
            out<<best[i]<<" ";
        out<<"\n";
    }
    in.close();
    out.close();
    return 0;
}