Cod sursa(job #2806154)

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

using namespace std;
FILE* f, * g;

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

void bf(int nod)
{
    d[nod] = 0;
    q.push_back(nod);
    viz[nod] = 1;
    ++fr[nod];
    while (!q.empty())
    {
        nod = q.front();
        q.pop_front();
        viz[nod] = 0;
        for (int i = 0;i < graph[nod].size();++i)
            if (d[graph[nod][i].ve] > d[nod] + graph[nod][i].co)
            {
                d[graph[nod][i].ve] = d[nod] + graph[nod][i].co;
                if (!viz[graph[nod][i].ve])
                {
                    viz[graph[nod][i].ve] = 1;
                    q.push_back(graph[nod][i].ve);
                    ++fr[graph[nod][i].ve];
                    if (fr[graph[nod][i].ve] > n)
                    {
                        fprintf(g, "Ciclu negativ!");
                        ok = 1;
                        return;
                    }
                }
            }
    }
}
int main()
{
    f = fopen("bellmanford.in", "r");
    g = fopen("bellmanford.out", "w");
    int m, x, y, z;
    fscanf(f, "%d %d", &n, &m);
    for (int i = 1;i <= m;++i)
    {
        fscanf(f, "%d %d %d", &x, &y, &z);
        graph[x].push_back({ y,z });
    }
    for (int i = 1;i <= n;++i)
        d[i] = INF;
    bf(1);
    if (!ok)
        for (int i = 2;i <= n;++i)
            fprintf(g, "%d ", d[i]);
    fclose(f);
    fclose(g);
    return 0;
}