Cod sursa(job #1040522)

Utilizator dnprxDan Pracsiu dnprx Data 24 noiembrie 2013 16:46:37
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include<fstream>
#include<vector>
#include<queue>
#define infinit 1000000000

using namespace std;

struct muchie
{
    int nod, cost;
};

vector<muchie> L[50002];
int n, d[50002], contor[50002];
bool viz[50002];
queue<int> q;

void Citire()
{
  int i, x, m;
  muchie w;
  ifstream fin("bellmanford.in");
  fin >> n >> m;

  for (i = 1; i <= m; i++)
  {
    fin >> x >> w.nod >> w.cost;
    L[x].push_back(w);
  }
  fin.close();
}

void BellmanFord()
{
    bool areCircuiteNegative;
    int i, x, c;
    unsigned int j;
    muchie w;

    // init:
    areCircuiteNegative = false;
    for (i = 2; i <= n; i++)
        d[i] = infinit;
    d[1] = 0;
    viz[1] = true;
    q.push(1);
    while (!q.empty() && !areCircuiteNegative)
    {
        x = q.front();
        q.pop();
        viz[x] = false;
        for (j = 0; j < L[x].size(); j++)
        {
            w = L[x][j];
            i = w.nod;
            c = w.cost;
            if (d[x] < infinit)
              if (d[i] > d[x] + c)
              {
                  d[i] = d[x] + c;
                  if (!viz[i])
                  {
                    if (contor[i] > n) areCircuiteNegative = true;
                    else
                    {
                        q.push(i);
                        viz[i] = true;
                        contor[i]++;
                    }
                  }
              }
        }
    }

    // afisare
    ofstream fout("bellmanford.out");
    if (!areCircuiteNegative)
    {
        for (int i = 2; i <= n; ++ i)
            fout << d[i] << " ";
    }
    else
        fout << "Ciclu negativ!\n";
    fout.close();
}

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