Cod sursa(job #931996)

Utilizator tsubyRazvan Idomir tsuby Data 28 martie 2013 17:23:09
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <cstdio>
#include <vector>
#include <queue>
#define NMAX 50005
#define INF 2000000000

using namespace std;

int n, nr[NMAX], cost[NMAX];
struct comp
{
    /// gen dijkstra
    bool operator () (const int &a, const int &b) const
    {
        return cost[a] > cost[b];
    }
};
struct nod
{
    int v;
    int cost;
};
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 (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()
{
    if (!bellmanford())
        printf ("Ciclu negativ!\n");
    else
    {
        for (int i = 2; i <= n; i++)
            if (cost[i] == INF)
                printf("0 ");
            else
                printf("%d ", cost[i]);
        printf("\n");
    }
}

int main()
{
    citire();
    afisare();
    return 0;
}