Cod sursa(job #3271662)

Utilizator axetyNistor Iulian axety Data 26 ianuarie 2025 20:07:01
Problema Algoritmul Bellman-Ford Scor 85
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <fstream>
#include <utility>
#include <vector>
#include <stdlib.h>
#include <cstring>
#include <set>
#include <queue>

#define nmax 50000
#define Inf 10000000
using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
vector<pair<int, int>> Graf[nmax + 1];
int dist[nmax], viz[nmax];
vector<int> Nciclu;
void bellmanford(int varf)
{
    for (int i = 1; i <= n; i++)
        dist[i] = Inf;
    dist[varf] = 0;
    queue<pair<int, int>> q;
    q.push({0, varf});
    viz[varf] = 1;
    bool ok = 1;
    while (!q.empty() && ok == 1)
    {
        int nod = q.front().second;
        q.pop();
        viz[nod]++;
        if (viz[nod] == n)
        {
            ok = 0;
            break;
        }
        else
        {
            for (auto neigh : Graf[nod])
            {
                if (dist[neigh.first] > dist[nod] + neigh.second)
                {
                    dist[neigh.first] = dist[nod] + neigh.second;
                    q.push({dist[neigh.first], neigh.first});
                }
            }
        }
    }
    if (ok == 0)
    {
        fout << "Ciclu negativ!";
    }
    else
    {
        for (int i = 2; i <= n; i++)
        {
            fout << dist[i] << " ";
        }
    }
}
int main()
{

    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        Graf[x].push_back({y, c});
    }
    bellmanford(1);
    return 0;
}