Cod sursa(job #2806151)

Utilizator namesurname01Name Surname namesurname01 Data 22 noiembrie 2021 13:37:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#define N 50002
#include <vector>
#define INF 2000000000
#include <deque>

using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

struct bla
{
    int ve, co;
};
vector <bla> graph[N];
int fr[N], dr[N], n;
deque <int> q;

void bf(int nod)
{
    q.push_back(nod);
    while (!q.empty())
    {
        nod = q.front();
        q.pop_front();
        for (int i = 0;i < graph[nod].size();++i)
        {
            int vee = graph[nod][i].ve;
            if (dr[vee] > dr[nod] + graph[nod][i].co)
            {
                dr[vee] = dr[nod] + graph[nod][i].co;
                q.push_back(vee);
                ++fr[vee];
                if (fr[vee] > n)
                {
                    g << "Ciclu negativ!";
                    return;
                }
            }
        }
    }
    for (int i = 2;i <= n;++i)
        g << dr[i] << ' ';
}
int main()
{
    int m, x, y, c;
    f >> n >> m;
    while (m--)
    {
        f >> x >> y >> c;
        graph[x].push_back({ y,c });
    }
    for (int i = 2;i <= n;++i) dr[i] = INF;
    bf(1);

    f.close();
    g.close();
    return 0;
}