Cod sursa(job #1643891)

Utilizator crysstyanIacob Paul Cristian crysstyan Data 9 martie 2016 20:37:18
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#define NMAX 50005
#define inf 2000000000

using namespace std;

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

int used[NMAX], d[NMAX], i, j, n, m, x, y, cost;
bool exista = 0;
vector < pair < int, int > > v[NMAX];
queue < int > q;

void bellman()
{
    q.push(1);
    d[1] = 0;

    for (int i = 2; i <= n; ++ i)
        d[i] = inf;

    while (!q.empty())
    {
        int curr = q.front();
        q.pop();

        for (auto & it : v[curr])
            if (d[it.first] > d[curr] + it.second)
        {
            if (used[it.first] > n)
                exista = 1;
            else
            {
                used[it.second] ++;
                d[it.first] = d[curr] + it.second;
                q.push(it.first);
            }
        }
    }
}

int main()
{
    f >> n >> m;

    for (i = 1; i <= m; ++ i)
    {
        f >> x >> y >> cost;
        v[x].push_back(make_pair(y, cost));
    }

    bellman();

    if (exista)
    {
        g << "Ciclu negativ!" << '\n';
        return 0;
    }

    for (i = 2; i <= n; ++ i)
        g << d[i] << " ";
    return 0;
}