Cod sursa(job #2819254)

Utilizator Mirela_MagdalenaCatrina Mirela Mirela_Magdalena Data 18 decembrie 2021 10:33:24
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#define MAX 0x3f3f3f3f
#define NMAX 50005
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

int n,m;
int intrari_in_queue[NMAX], viz[NMAX];
int cost[NMAX];
vector<pair<int,int>> adiacenta[NMAX];
queue<int> q;



void citire()
{
    int x,y,c;
    f >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        f >> x >> y >> c;
        adiacenta[x].push_back({y,c});
    }
}

void init()
{
    for(int i = 1; i<=n; i++)
        cost[i] = MAX;
}

void Bellman()
{
    q.push(1);
    cost[1] = 0;
    viz[1] = 1;

    while(!q.empty())
    {
        int nod_curent = q.front();
        int cost_curent = cost[nod_curent];
        q.pop();
        viz[nod_curent] = 0;

        for(auto &x:adiacenta[nod_curent])
        {
            if(cost[x.first] > cost[nod_curent] + x.second)
            {
                cost[x.first] = cost[nod_curent] + x.second;
                if(viz[x.first] == 0)
                {
                    q.push(x.first);
                    viz[x.first] = 1;
                }
                intrari_in_queue[x.first]++;
                if(intrari_in_queue[x.first]>=n)
                {
                    g<<"Ciclu negativ!";
                    exit(0);
                }
            }
        }
    }
}
void afisare()
{
    for (int i = 2; i <= n; i++)
    {
        if (cost[i] >= MAX)
            g << "0 ";
        else
            g << cost[i] << " ";
    }
}
int main()
{
    citire();
    init();
    Bellman();
    afisare();
    return 0;
}