Cod sursa(job #3285007)

Utilizator PsyDuck1914Feraru Rares-Serban PsyDuck1914 Data 12 martie 2025 13:53:28
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 5e4;

int dist[NMAX + 1], cntQ[NMAX + 1];//sa stiu de cate ori a aparurt nodul in coada maxim n-1 ori pt solutie fara ciclu de cost negativ

struct ura{
    
    int first, second;
    
};
vector<ura> adj[NMAX + 1];
bool inQ[NMAX + 1];//sa stou daca e in coada
bool e_ciclu = true;
queue<int> q;

int n, m;

void belly(int nod){
    
    q.push(nod);
    dist[nod] = 0;
    
    while(!q.empty()){
        
        int fromnod = q.front();
        q.pop();
        
        //cout << fromnod << endl;
        
        inQ[fromnod] = false;//nu mai e in coada gen
        
        if(cntQ[fromnod] >= n){
            
            e_ciclu = false;
            return;
            
        }
        
        for(auto next : adj[fromnod]){
            
            int tonod = next.first;
            int tocost = next.second;
            
            if(dist[tonod] > dist[fromnod] + tocost){
                
                
                dist[tonod] = dist[fromnod] + tocost;
                
                if(!inQ[tonod])
                    inQ[tonod] = true, q.push(tonod);
                    
                cntQ[tonod] ++;
                
            }
            
        }
        
    }
    
}

int main()
{
    
    f.tie(NULL);
    ios_base::sync_with_stdio(false);
    
    f >> n >> m;
    
    for(int i=1; i<=m; i++){
        
        int x, y, cost;
        f >> x >> y >> cost;
        
        adj[x].push_back({y, cost});
        
    }
    
    fill(dist + 2, dist + 1 + NMAX, 2e9);
    
    belly(1);
    
    if(e_ciclu == false){
        
        g << "Ciclu negativ!";
        return 0;
        
    }
    
    for(int i=2; i<=n; i++)
        g << dist[i] << ' ';

    return 0;
}