Cod sursa(job #1877446)

Utilizator ChiriGeorgeChiriluta George-Stefan ChiriGeorge Data 13 februarie 2017 12:45:00
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 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");

struct graph{
    int neighbour;
    int cost;
};
int n, m, freq[NMAX], x, y, c, i, d[NMAX], v, added[NMAX];
queue <int> Q;
vector <graph> G[NMAX];

int main()
{
    fin >> n >> m;
    for(i = 1; i <= n; i++)
    {
        fin >> x >> y >> c;
        graph p;
        p.neighbour = y;
        p.cost = c;
        G[x].push_back(p);
    }
    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 < G[v].size(); i++)
        {
            int neigh = G[v][i].neighbour;
            c = G[v][i].cost;
            if(d[neigh] > d[v] + c)
            {
                d[neigh] = d[v] + c;
                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;
}