Cod sursa(job #1877428)

Utilizator ChiriGeorgeChiriluta George-Stefan ChiriGeorge Data 13 februarie 2017 12:27:05
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <queue>
#include <vector>
#include <cstring>

#define NMAX 50005
#define Inf 0x3f3f3f3f

using namespace std;

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

int n, m, freq[NMAX], x, y, cost, i, d[NMAX], v, added[NMAX];
queue <int> Q;
vector <int> Neighbours[NMAX], Costs[NMAX];

int main()
{
    fin >> n >> m;
    for(i = 1; i <= n; i++)
    {
        fin >> x >> y >> cost;
        Neighbours[x].push_back(y);
        Costs[x].push_back(cost);
    }
    memset(d, Inf, sizeof(d));
    d[1] = 0;
    Q.push(1);
    added[1] = 1;
    while(!Q.empty())
    {
        v = Q.front();
        Q.pop();
        added[v] = 0;
        for(i = 0; i < Neighbours[v].size(); i++)
        {
            int neigh = Neighbours[v][i];
            cost = Costs[v][i];
            if(d[neigh] > d[v] + cost)
            {
                d[neigh] = d[v] + cost;
                if(added[neigh] == 0)
                {
                    Q.push(neigh);
                    added[neigh] = 1;
                    if(++freq[neigh] >= n)
                    {
                        fout << "Ciclu negativ!\n";
                        return 0;
                    }
                }
            }
        }
    }
    for(i = 2; i <= n; i++)
        fout << d[i] << ' ';
    fout << '\n';
    return 0;
}