Cod sursa(job #3280235)

Utilizator Torna3oVirtopeanu Andrei Torna3o Data 25 februarie 2025 20:35:42
Problema Algoritmul Bellman-Ford Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const long long INF = (1LL << 60);
vector< pair < int, int > > G[50001];
queue<int> q;
int cnt[50001], n;
long long cost[50001];
bool neg = false;

void bellmanford()
{
    for(int i = 1; i <= n; i++)
    {
        cost[i] = INF;
    }
    cost[1] = 0;
    q.push(1);
    while(!q.empty())
    {
        int node = q.front();
        q.pop();
        for(auto it : G[node])
        {
            int nn = it.first;
            int nd = it.second;
            if(cost[node] + nd < cost[nn])
            {
                cost[nn] = cost[node] + nd;
                cnt[nn]++;
                q.push(nn);
                if(cnt[nn] > n)
                {
                    out << "Ciclu negativ!";
                    neg = true;
                    while(!q.empty())
                    {
                        q.pop();
                    }
                }
            }
        }
    }
}


int main()
{
    int m, i, x, y, c;
    in >> n >> m;
    for(i = 1; i <= m; i++)
    {
        in >> x >> y >> c;
        G[x].push_back({y, c});
    }

    bellmanford();
    if(neg == false)
    {
        for(i = 2; i <= n; i++)
        {
            out << cost[i] << " ";
        }
    }
    return 0;
}