Cod sursa(job #2159134)

Utilizator papinub2Papa Valentin papinub2 Data 10 martie 2018 19:24:00
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#define mp make_pair
#define inf 50000005

using namespace std;

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

const int Nmax = 50005;

vector<int> d(Nmax);
vector<pair<int, int> > A[Nmax];

struct cmp
{
    bool operator()(int x, int y)
    {
        return d[x] > d[y];
    }
};
priority_queue<int, vector<int>, cmp> Q;


void Dijkstra (int Start, int n, bool&sol, vector<int>&cnt, vector<bool>&OK)
{
    for (int i = 2; i <= n; i++)
        d[i] = inf;

    Q.push(Start);

    while (!Q.empty())
    {
        if (sol == 0)
            break;

        int nod = Q.top();
        Q.pop();
        OK[nod] = 0;

        for (auto i = 0; i < A[nod].size(); i++)
        {
            int nod_curent = A[nod][i].first;
            int cost_curent = A[nod][i].second;
            int lungime = d[nod] + cost_curent;

            if (lungime < d[nod_curent])
            {
                d[nod_curent] = lungime;

                if (OK[nod_curent] == 0)
                {
                    Q.push(nod_curent);
                    OK[nod_curent] = 1;
                    cnt[nod_curent]++;
                    if (cnt[nod_curent] == n)
                        sol = 0;
                }
            }
        }
    }
}

int main()
{
    int n, m;
    bool sol = 1;
    in >> n >> m;

    vector<int> cnt(n + 1);
    vector<bool> OK(n + 1);

    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;

        A[x].push_back(mp(y, c));
    }

    Dijkstra(1, n, sol, cnt, OK);

    if (sol == 0)
    {
        out << "Ciclu negativ!";
        return 0;
    }

    for (int i = 2; i <= n; i++)
        out << d[i] << ' ';
    return 0;
}