Cod sursa(job #2372290)

Utilizator tziplea_stefanTiplea Stefan tziplea_stefan Data 6 martie 2019 23:36:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

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

const int VAL=50005;
const int INF=1000000000;

int N, M, i, j, A, B, C;
int dist[VAL], ap[VAL], nod;
bool inqueue[VAL], gasit;
vector < pair <int, int> > G[VAL];
vector < pair <int, int> > :: iterator it;
queue <int> Q;

void BFS()
{
    Q.push(1);
    inqueue[1]=true;
    ap[1]++;
    while (Q.empty()==false)
    {
        nod=Q.front();
        Q.pop();
        inqueue[nod]=false;
        for (it=G[nod].begin(); it!=G[nod].end(); it++)
        {
            A=it->first;
            C=it->second;
            if (dist[A]>dist[nod]+C)
            {
                dist[A]=dist[nod]+C;
                if (inqueue[A]==false)
                {
                    inqueue[A]=true;
                    Q.push(A);
                    ap[A]++;
                    if (ap[A]==N)
                    {
                        gasit=true;
                        return;
                    }
                }
            }
        }
    }
}

int main()
{
    fin >> N >> M;
    for (i=1; i<=M; i++)
    {
        fin >> A >> B >> C;
        G[A].push_back({B, C});
    }
    dist[1]=0;
    for (i=2; i<=N; i++)
        dist[i]=INF;
    BFS();
    if (gasit==true)
        fout << "Ciclu negativ!";
    else
        for (i=2; i<=N; i++)
            fout << dist[i] << " ";
    fin.close();
    fout.close();
    return 0;
}