Cod sursa(job #954773)

Utilizator gabriel.badeaGabriel Badea gabriel.badea Data 29 mai 2013 23:51:23
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include<stdio.h>
#include<vector>
#include<deque>
#include<algorithm>
#include<iostream>
using namespace std;

int n, m, i, x, y, c, p, u, viz[50001], dist[50001];
vector<pair<int,int> > a[50001];
deque<int> d;

void afis()
{
    for(i = 2; i <= n; ++i)
        printf("%d ", dist[i]);
}

void bellman(int x)
{
    u = p = 1;
    d.push_back(x);
    while(!d.empty())
    {
        x = d.front();
        d.pop_front();
        for(i = 0; i < a[x].size(); ++i)
        {
            y = a[x][i].first;
            c = a[x][i].second;

            if((viz[y] == 0 || dist[y] > dist[x] + c) && y != 1) viz[y]++, dist[y] = dist[x] + c, d.push_back(y);
            if(viz[y] >= n)
            {
                printf("Ciclu negativ!");
                return;
            }
        }
    }
    afis();
}

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

    scanf("%d %d", &n, &m);
    for(i = 1; i <= m; ++i)
    {
        scanf("%d %d %d", &x, &y, &c);
        a[x].push_back(make_pair(y,c));
    }
    bellman(1);
    return 0;
}