Cod sursa(job #1520741)

Utilizator tc_iuresiures tudor-cristian tc_iures Data 9 noiembrie 2015 12:42:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

const int Nmax = 50005;
const int INF  = 2000000000;

int N, M;
bool isInQ[Nmax], negativeCycles;
vector<pair<int,int>> G[Nmax];
queue<int> Q;
int D[Nmax];
int nrInQ[Nmax];

void read()
{
   ifstream f("bellmanford.in");
   f >> N >> M;
   for(int i = 0; i < M; i ++)
   {
      int x, y, z;
      f >> x >> y >> z;
      G[x].push_back(make_pair(y,z));
   }
   f.close();
}

void BellmanFord(int k)
{
   for(int i = 1; i <= N; i ++)
   {
      D[i] = INF;
   }
   D[k] = 0;
   isInQ[k] = true;
   Q.push(k);
   nrInQ[k] ++;
   while((!Q.empty()) && (!negativeCycles))
   {
      int top = Q.front();
      isInQ[top] = false;
      Q.pop();
      for(int i = 0; i < G[top].size(); i ++)
      {
         int Ngh = G[top][i].first;
         int wgt = G[top][i].second;
         if(D[Ngh] > D[top]+wgt)
         {
            D[Ngh] = D[top]+wgt;
            if(!isInQ[Ngh])
            {
               if(nrInQ[Ngh] > N)
               {
                  negativeCycles = true;
               }
               else
               {
                  isInQ[Ngh] = true;
                  nrInQ[Ngh] ++;
                  Q.push(Ngh);
               }
            }
         }
      }

   }
}

void print()
{
   ofstream g("bellmanford.out");
   if(negativeCycles)
   {
      g << "Ciclu negativ!";
   }
   else
   {
      for(int i = 2; i <= N; i ++)
      {
         g << D[i] << " ";
      }
   }
   g.close();
}

int main()
{
    read();
    BellmanFord(1);
    print();
    return 0;
}