Cod sursa(job #2792034)

Utilizator PaulTPaul Tirlisan PaulT Data 31 octombrie 2021 18:31:23
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <queue>
using namespace std;

const int Inf = 0x3f3f3f3f;
int n, m;
vector<vector<pair<int, int>>> G;
vector<int> d;

void Read();
bool BellmanFord(int x, vector<int>& d);

int main()
{
    Read();
    
    ofstream fout("bellmanford.out");
    if (!BellmanFord(1, d))
        fout << "Ciclu negativ!";
    else
    {
        for (int i = 2; i <= n; i++)
            fout << d[i] << ' ';
    }
}

bool BellmanFord(int x, vector<int>& d)
{
    d = vector<int>(n + 1, Inf);
    queue<int> Q;
    vector<bool> inQueue = vector<bool>(n + 1);
    vector<int> cnt = vector<int>(n + 1);
    
    d[x] = 0;
    Q.emplace(x);
    inQueue[x] = true;
    cnt[x]++;
    int y, w;
    while (!Q.empty())
    {
        x = Q.front();
        Q.pop();
        inQueue[x] = false;
        for (const auto& p : G[x])
        {
            y = p.first;
            w = p.second;
            if (d[y] > d[x] + w)
            {
                d[y] = d[x] + w;
                if (!inQueue[y])
                {
                    Q.emplace(y);
                    inQueue[y] = true;
                    cnt[y]++;
                    if (cnt[y] == n)
                        return false;
                }
            }
        }
    }
    return true;
}

void Read()
{
    ifstream fin("bellmanford.in");
    fin >> n >> m;
    G = vector<vector<pair<int, int>>>(n + 1);
    
    int x, y, w;
    while (m--)
    {
        fin >> x >> y >> w;
        G[x].emplace_back(y, w);
    }
}