Cod sursa(job #1463795)

Utilizator petru.cehanCehan Petru petru.cehan Data 21 iulie 2015 15:56:38
Problema Algoritmul Bellman-Ford Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <fstream>
#define inf 1001

using namespace std;

ifstream fin ("bellmanford.in") ;
ofstream fout ("bellmanford.out") ;

int N , M ;

struct nod
{
    int info , cost ;
    nod * next ;
} ;

nod * L [50001] ;

void Citire ()
{
  fin >> N >> M ;
  int a , b , c ;
  while ( M >= 1 )
  {
      fin >> a >> b >> c ;
      nod * p = new nod ;
      p->info = b ;
      p->cost = c ;
      p->next = L [a] ;
      L [a] = p ;

      -- M ;
  }
}

int coada [50001] , cst [50001] , iterari_nod [50001] , lg_c ;
bool in_coada [50001] ;

void BellmanFord ()
{
    // Initializare
    for ( int i = 2 ; i <= N ; ++ i )
           cst [i] = inf ;  // mai putin nodul sursa

    coada [ ++ lg_c ] = 1 ;
    in_coada [ 1 ] = true ;

    while ( lg_c > 0 ) // cat timp sunt elemente in coada
    {
        int nd = coada [1] ;
        // POP COADA
        for ( int i = 1 ; i < lg_c ; ++ i )
              coada [i] = coada [i+1] ;
        -- lg_c ;
        in_coada [ nd ] = false ;

        for ( nod * p = L [nd] ; p != 0 ; p = p->next )
        {
            if ( cst [p->info] > cst [nd] + p->cost )
                    cst [p->info] = cst [nd] + p->cost ; // minimizam distanta

            if ( in_coada [ p->info ] == 0 )  // nu se afla vecinul in coada
                    {
                        coada [ ++ lg_c ] = p->info ; // il introduc
                        in_coada [ p->info ] = true ;
                        ++ iterari_nod [ p->info ] ; // s-a trecut o data in plus prin el
                        if ( iterari_nod [ p->info ] > N ) // daca s-a trecut de mai mult de N ori prin el
                             {
                                 fout << "Ciclu negativ!\n" ;
                                 return ;
                             }
                    }
        }

    }

 for ( int i = 2 ; i <= N ; ++ i )
      fout << cst [i] << " " ;
}

int main()
{
    Citire () ;
    BellmanFord() ;
    return 0;
}