Cod sursa(job #1791660)

Utilizator PaulStighiStiegelbauer Paul-Alexandru PaulStighi Data 29 octombrie 2016 16:26:58
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include<fstream>
#include<vector>
#include<queue>
#define NMax 50005
#define oo 1<<30
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

int N,M;
int D[NMax],NrQ[NMax];
bool OK = 1,InQ[NMax];

vector < pair <int,int> > G[NMax];
queue <int> Q;

void Read()
{
    fin>>N>>M;

    for(int i = 1 ; i <= M ; ++i)
    {
        int x,y,c;  fin>>x>>y>>c;
        G[x].push_back(make_pair(y,c));
    }
}

void Solve()
{
    for(int i = 2 ; i <= N ; ++i)
        D[i] = oo;

    Q.push(1);
    InQ[1] = 1;
    NrQ[1]++;

    while(!Q.empty() && OK)
    {
        int Nod = Q.front();
        Q.pop();    InQ[Nod] = 0;

        for(int i = 0 ; i < (int) G[Nod].size() ; ++i)
        {
            int Vecin = G[Nod][i].first;
            int Cost = G[Nod][i].second;

            if(D[Vecin] > D[Nod] + Cost)
            {
                D[Vecin] = D[Nod] + Cost;

                if(InQ[Vecin] == 0)
                {
                    Q.push(Vecin);
                    InQ[Vecin] = 1;
                    NrQ[Vecin]++;

                    if(NrQ[Vecin] > N)  OK = 0;
                }
            }
        }
    }
}

void Print()
{
    if(!OK) fout<<"Ciclu negativ!\n";
    else
    {
        for(int i = 2 ; i <= N ; ++i)
            fout<<D[i]<<" ";
        fout<<"\n";
    }
}

int main()
{
    Read();
    Solve();
    Print();

    fin.close();
    fout.close();
    return 0;
}