Cod sursa(job #711488)

Utilizator vlad2901Vlad Berindei vlad2901 Data 12 martie 2012 11:27:46
Problema Algoritmul Bellman-Ford Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <cstdio>
#include <queue>

#define NMAX 50001
#define MMAX 250001
#define INF 250000001

using namespace std;

vector<vector<pair<int, int> > > v(NMAX); //lista de vecini cu costuri
int d[NMAX];

int inqueue[NMAX], N, M;

int negativ()
{
    for(int i=0;i<N;++i)
    {
        for(vector<pair<int, int> >::iterator it = v[i].begin();it!=v[i].end();++it)
        {
            if(d[it->first] > d[i] + it->second)
            {
                return 1;
            }
        }
    }
    return 0;
}

int main()
{

    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);

    scanf("%d %d", &N, &M);

    for(int i=0;i<M;++i)
    {
        int x, y, c;
        scanf("%d %d %d", &x, &y, &c);
        v[x].push_back(make_pair(y,c));
    }

    for(int i=0;i<=N;++i)
    {
        d[i] = INF;
    }

    queue<int> Q;

    Q.push(1);
    inqueue[1] = 1;
    long long step = 0;
    d[1] = 0;

    while(!Q.empty() && step < N * M * 1LL)
    {
        int current;
        ++step;
        current = Q.front();
        Q.pop();
        inqueue[current] = 0;


        for(vector<pair<int, int> >::iterator it = v[current].begin();it!=v[current].end();++it)
        {
            if(d[it->first] > d[current] + it->second)
            {
                d[it->first] = d[current] + it->second;

                if(!inqueue[it->first])
                {
                    Q.push(it->first);
                    inqueue[it->first] = 1;
                }
            }
        }
    }

    if(negativ())
    {
        printf("Ciclu negativ!\n");
    }
    else
    {
        for(int i=2;i<=N;++i)
        {
            printf("%d ", d[i]);
        }
        printf("\n");
    }

    return 0;
}