Cod sursa(job #884802)

Utilizator simaghitaSima Gheorghe Eugen simaghita Data 21 februarie 2013 12:42:33
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include<fstream>
#include<vector>
#include<queue>

using namespace std;

struct Nod
{
    int x,cost ;
};
int n,m,d[50010];
vector <Nod> L[50010];
queue <int> q;
void Citire()
{
    int y,i;
    freopen("bellmanford.in","r",stdin);
    Nod aux;
    scanf("%d%d", &n , &m);
    for(i=1;i<=m;i++)
    {
        scanf("%d %d %d", &y , &aux.x, &aux.cost);
        L[y].push_back(aux);
    }
}
int Bellmanford()
{
    int k,i;
    Nod aux;
    q.push(1);
    while(!q.empty())
    {
        k=q.front();
        q.pop();
        int N=L[k].size();
        for(i=0;i<N;i++)
        {
            aux=L[k][i];
            if(d[aux.x] > d[k] + aux.cost)
            {
                d[aux.x]=d[k]+aux.cost;
                q.push(aux.x);
                if(d[aux.x] > d[k] + aux.cost)
                    return 0;
            }
        }
    }
    return 1;
}
void Initializare()
{
    int i;
    for(i=1;i<=n;i++)
        d[i]=2000000000;
    d[1]=0;
}
int main()
{
    freopen("bellmanford.out","w",stdout);
    Citire();
    Initializare();
    int ciclu,i;
    ciclu=Bellmanford();
    if(!ciclu)
    {
        printf("Ciclu negativ!\n");
        return 0;
    }
    for(i=2;i<=n;i++)
        printf("%d ", d[i]);
    printf("\n");
    return 0;
}