Cod sursa(job #3269544)

Utilizator maryyMaria Ciutea maryy Data 19 ianuarie 2025 15:34:16
Problema Algoritmul Bellman-Ford Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int NMAX = 50000, INF = 1e9;
vector <pair<int, int>> graph[NMAX+1];
vector <int> dist(NMAX+1, INF), cnt(NMAX+1, 0);
bitset <NMAX+1> inq;
int n, m;
bool bellman(int start)
{
    queue <int> q;
    q.push(start);
    inq[start] = 1;
    dist[start] = 0;
    cnt[start]++;
    while(!q.empty())
    {
        int node = q.front();
        q.pop();
        inq[node] = 0;
        for(auto [next, price]:graph[node])
        {
            if(inq[next] == 0 && dist[node] + price < dist[next])
            {
                dist[next] = dist[node] + price;
                cnt[next]++;
                inq[next] = 1;
                q.push(next);
                if(cnt[next] >= n)
                {
                    return 1;
                }
            }
        }
    }
    return 0;
}
int main()
{
    int a, b, c;
    in>>n>>m;
    for(int i=1; i<=m; i++)
    {
        in>>a>>b>>c;
        graph[a].push_back({b, c});
    }
    bool rez = bellman(1);
    if(rez == 1)
    {
        out<<"Ciclu negativ!";
        return 0;
    }
    for(int i=2; i<=n; i++)
    {
        out<<dist[i]<<" ";
    }
    return 0;
}