Cod sursa(job #2924692)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 8 octombrie 2022 18:00:25
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

const int max_size = 5e4 + 1, INF = 2e9 + 1;

struct str{
    int to, cost;
};

vector <str> mc[max_size];
int d[max_size], viz[max_size], n;
queue <int> q;

bool bfs ()
{
    q.push(1);
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        viz[nod]++;
        if (viz[nod] == n + 1)
        {
            return false;
        }
        for (auto f : mc[nod])
        {
            if (d[nod] + f.cost < d[f.to])
            {
                d[f.to] = d[nod] + f.cost;
                q.push(f.to);
            }
        }
    }
    return true;
}

int main ()
{
    int m;
    in >> n >> m;
    for (int i = 2; i <= n; i++)
    {
        d[i] = INF;
    }
    while (m--)
    {
        int x, y, z;
        in >> x >> y >> z;
        mc[x].push_back({y, z});
    }
    if (!bfs())
    {
        out << "Ciclu negativ!";
    }
    else
    {
        for (int i = 2; i <= n; i++)
        {
            out << d[i] << " ";
        }
    }
    in.close();
    out.close();
    return 0;
}