Cod sursa(job #933835)

Utilizator visanrVisan Radu visanr Data 30 martie 2013 12:51:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

#define PI pair<int, int>
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define Nmax 50010
#define forit(it, v) for(typeof((v).begin()) it = (v).begin(); it != (v).end(); ++ it)
#define Inf 0x3f3f3f3f

int N, M, X, Y, C, Dist[Nmax], Ap[Nmax];
bool InQueue[Nmax];
vector<PI> G[Nmax];

void BellmanFord()
{
    for(int i = 1; i <= N; ++ i) Dist[i] = Inf;
    Dist[1] = 0;
    queue<int> Q;
    Q.push(1);
    Ap[1] = 1;
    InQueue[1] = 1;
    while(!Q.empty())
    {
        int Node = Q.front();
        Q.pop();
        InQueue[Node] = 0;
        if(Ap[Node] > N)
        {
            printf("Ciclu negativ!");
            exit(0);
        }
        forit(it, G[Node])
            if(Dist[it -> f] > Dist[Node] + it -> s)
            {
                Dist[it -> f] = Dist[Node] + it -> s;
                if(!InQueue[it -> f])
                {
                    InQueue[it -> f] = 1;
                    Ap[it -> f] ++;
                    Q.push(it -> f);
                }
            }
    }
    for(int i = 2; i <= N; ++ i) printf("%i ", Dist[i]);
}

int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    int i;
    scanf("%i %i", &N, &M);
    for(i = 1; i <= M; ++ i)
    {
        scanf("%i %i %i", &X, &Y, &C);
        G[X].pb(mp(Y, C));
    }
    BellmanFord();
    return 0;
}