Cod sursa(job #931990)

Utilizator tsubyRazvan Idomir tsuby Data 28 martie 2013 17:18:12
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <cstdio>
#include <vector>
#include <queue>

#define NMAX 50001
#define INF 999999999

using namespace std;

struct nod
{
    int v;
    int cost;
};

struct comp
{
    /// gen dijkstra
    bool operator () (const int &a, const int &b) const
    {
        return cost[a] > cost[b];
    }
};

int n, nr[NMAX], cost[NMAX];
vector <nod> G[NMAX];
priority_queue <int, vector <int>, comp> Q;

void citire()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    int m, x;
    nod y;

    scanf ("%d %d", &n, &m);
    for(int i = 0; i < m; i++)
    {
        scanf ("%d %d %d", &x, &y.v, &y.cost);
        G[x].push_back(y);
    }
}

bool bellmanford()
{
    for (int i = 2; i <= n; cost[i] = INF, ++ i);
    Q.push(1);

    while (!Q.empty())
    {
        int v = Q.top();
        Q.pop();

        for (unsigned int i = 0; i < G[v].size(); ++ i)
        {
            nod aux = G[v][i];

            if (cost[v] + aux.cost < cost[aux.v])
            {
                cost[aux.v] = cost[v] + aux.cost;
                Q.push(aux.v);
                ++ nr[v];
            }
        }
        if (nr[v] > n)
            return 0;
    }
    return 1;
}

void afisare()
{
    for (int i = 2; i <= n; ++ i)
        if (cost[i] == INF)
            printf("0 ");
        else
            fprintf("%d ", cost[i]);
    printf("\n");
}

int main()
{
    citire();
    if (!bellmanford())
        fprintf (outFile, "Ciclu negativ!");
    else
        afisare();

    return 0;
}