Cod sursa(job #3304302)

Utilizator AndreiEsteNebunAndrei Mateescu AndreiEsteNebun Data 22 iulie 2025 13:44:25
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <queue>
#include <vector>

using namespace std;

string filename = "bellmanford";

ifstream fin(filename + ".in");
ofstream fout(filename + ".out");

const int NMAX = 50000;
const int INF = 1e9;

vector <pair <int, int>> adj[NMAX + 5];
int dist[NMAX + 5];
int nodes[NMAX + 5];
bool inQueue[NMAX + 5];

int main()
{
    ///chiar nu stiu daca sa scriu codul atat de spatios sau nu
    int n, m;
    fin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int u, v, d;
        fin >> u >> v >> d;
        adj[u].push_back({v, d});
    }
    for (int i = 1; i <= n; ++i)
    {
        dist[i] = INF;
        inQueue[i] = false;
    }
    queue <int> q;
    dist[1] = 0;
    nodes[1] = 1;
    q.push(1);
    inQueue[1] = true;

    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        inQueue[node] = false;

        if (nodes[node] > n)
        {
            fout << "Ciclu negativ!";
            return 0;
        }

        for (auto x : adj[node])
        {
            if (dist[x.first] > dist[node] + x.second)
            {
                dist[x.first] = dist[node] + x.second;
                nodes[x.first] = nodes[node] + 1;
                if (!inQueue[x.first])
                {
                    q.push(x.first);
                    inQueue[x.first] = true;
                }
            }
        }
    }
    for (int i = 2; i <= n; i++)
    {
        fout << dist[i] << ' ';
    }
    return 0;
}