Cod sursa(job #3128728)

Utilizator rapidu36Victor Manz rapidu36 Data 10 mai 2023 17:06:58
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

const int N = 50000;
const int INF = 1 << 30;

struct succesor
{
    int vf, c;
};

vector <succesor> ls[N+1];
queue <int> q;
int n, d[N+1], nr_in_q[N+1];
bool in_q[N+1];

bool bf_moore()
{
    for (int i = 2; i <= n; i++)
    {
        d[i] = INF;
    }
    d[1] = 0;
    q.push(1);
    in_q[1] = true;
    nr_in_q[1]++;
    while (!q.empty())
    {
        int x =q.front();
        q.pop();
        for (auto s: ls[x])
        {
            int y = s.vf, c = s.c;
            if (d[x] + c < d[y])
            {
                d[y] = d[x] + c;
                nr_in_q[y]++;
                if (nr_in_q[y] == n)
                {
                    return false;
                }
                if (!in_q[y])
                {
                    q.push(y);
                }
            }
        }
    }
    return true;
}

int main()
{
    ifstream in("bellmanford.in");
    ofstream out("bellmanford.out");
    int m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        ls[x].push_back((succesor){y, c});
    }
    if (bf_moore())
    {
        for (int i = 2; i <= n; i++)
        {
            out << d[i] << " ";
        }
    }
    else
    {
        out << "Ciclu negativ!";
    }
    in.close();
    out.close();
    return 0;
}