Cod sursa(job #2027214)

Utilizator tziplea_stefanTiplea Stefan tziplea_stefan Data 25 septembrie 2017 19:43:51
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <queue>
#include <vector>
#define VAL 50005
#define INF 1000000000

using namespace std;

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

int N, M, i, j, a, b, c;
int dp[VAL], nr[VAL], nod;
bool ap[VAL], ok;
vector < pair <int, int> > G[VAL];
vector < pair <int, int> > :: iterator it;
queue <int> Q;

void BellmanFord()
{
    Q.push(1);
    nr[1]=1;
    ap[1]=true;
    while (Q.empty()==false)
    {
        nod=Q.front();
        Q.pop();
        for (it=G[nod].begin(); it!=G[nod].end(); it++)
        {
            if (dp[it->first]>dp[nod]+it->second)
            {
                dp[it->first]=dp[nod]+it->second;
                if (ap[it->first]==false)
                {
                    ap[it->first]=true;
                    nr[it->first]++;
                    if (nr[it->first]==N)
                    {
                        ok=true;
                        return;
                    }
                    Q.push(it->first);
                }
            }
        }
        ap[nod]=false;
    }
}


int main()
{
    fin >> N >> M;
    for (i=1; i<=M; i++)
    {
        fin >> a >> b >> c;
        G[a].push_back(make_pair(b, c));
    }
    for (i=2; i<=N; i++)
      dp[i]=INF;
    BellmanFord();
    if (ok==true)
      fout << "Ciclu negativ!";
    else
      for (i=2; i<=N; i++)
        fout << dp[i] << " ";
    fin.close();
    fout.close();
    return 0;
}