Cod sursa(job #931979)

Utilizator tsubyRazvan Idomir tsuby Data 28 martie 2013 17:12:35
Problema Algoritmul Bellman-Ford Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <cstdio>
#include <vector>
#include <algorithm>
#define maxn 50010
#define inf 1000000000

using namespace std;

struct muchie
{
    int a, b, c;
}e[250005];

int n, m, k, left, right, cost[maxn], f[maxn];
vector <int> v[maxn];
vector <pair<int, int> > h;

void initializare()
{
    cost[1]=0;
    for(int i = 2; i <= n; i++)
        cost[i] = inf;
    h.push_back(make_pair(0, 1));
    make_heap(h.begin(), h.end());
}

void prelucrare()
{
    pair<int, int> per;
    int nod, poz;
    int pas=0;
    while(h.size() && pas<=1LL*n*m)
    {
        pas++;
        pop_heap(h.begin(), h.end());
        per=h.back();
        h.pop_back();
        nod=per.second;
        f[nod]=0;
        for(int j=0; j<v[nod].size(); j++)
        {
            poz=v[nod][j];
            if(cost[e[poz].a]+e[poz].c<cost[e[poz].b])
            {
                cost[e[poz].b]=cost[e[poz].a]+e[poz].c;
                if(!f[e[poz].b])
                {
                    f[e[poz].b]=1;
                    h.push_back(make_pair(-cost[e[poz].b], e[poz].b));
                    push_heap(h.begin(), h.end());
                }
            }
        }
    }
}

int check_negativ()
{
    for(int i = 1; i <= m; i++)
        if(cost[e[i].a]+e[i].c < cost[e[i].b])
            return 1;
    return 0;
}

int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    initializare();
    scanf("%d%d", &n, &m);
    for(int i=1; i<=m; i++)
    {
        scanf("%d %d %d ", &e[i].a, &e[i].b, &e[i].c);
        v[e[i].a].push_back(i);
    }
    prelucrare();
    if(check_negativ() != 0)
    {
        printf("Ciclu negativ!\n");
        return 0;
    }
    for(int i=2; i<=n; i++)
        printf("%d ", cost[i]);
    return 0;
}