Cod sursa(job #1242291)

Utilizator alexb97Alexandru Buhai alexb97 Data 14 octombrie 2014 11:24:14
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

#define DIM 50010
#define INF 0x3f3f3f3f

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

vector<pair<int, int> > G[DIM];
queue<int> q;
bitset<DIM> inQueue;
int D[DIM], Nr[DIM];

int n, m, x, y, cost;

int main()
{
    fin >> n >> m;
    for (int i = 1;i <= m; i++)
    {
        fin >> x >> y >> cost;
        G[x].push_back({y, cost});
    }

    q.push(1);
    inQueue[1] = 1;
    D[1] = 0;
    for (int i = 2; i <=n; i++)
        D[i] = INF;

    while ( !q.empty() )
    {
        x = q.front(); // nod
        q.pop();
        inQueue[x] = 0;

        for (const auto& p : G[x])
        {
            y = p.first; cost = p.second;
            if (D[y] > D[x] + cost)
            {
                D[y] = D[x] + cost;
                if ( !inQueue[y] )
                {
                    Nr[y]++;
                    if (Nr[y] == n)
                    {
                        fout<<"Ciclu negativ!";
                        return 0;
                    }
                    q.push(y);
                    inQueue[y] = 1;
                }
            }
        }
    }

    for (int i = 2; i <= n; i++)
        fout << D[i] << " ";

    return 0;
}