Cod sursa(job #3349780)

Utilizator mtcmtcmtc mtc mtcmtc Data 2 aprilie 2026 14:57:34
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
vector<pair<int,int>>adj[50005];
int d[50005];
int main()
{
    for(int i=2;i<=50000;i++){
        d[i]=1e9;
    }
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        int x,y,c;
        cin>>x>>y>>c;
        adj[x].push_back({y,c});
    }
    for(int t=1;t<n;t++){
        for(int i=1;i<=n;i++){
            for(auto e:adj[i]){
                int j=e.first,c=e.second;
                if(d[i]!=1e9&&d[j]>d[i]+c){
                    d[j]=d[i]+c;
                }
            }
        }
    }
    bool ok=0;
    for(int i=1;i<=n;i++){
        for(auto e:adj[i]){
            int j=e.first,c=e.second;
            if(d[i]!=1e9&&d[j]>d[i]+c){
                ok=1;
            }
            if(ok==1) break;
        }
        if(ok==1) break;
    }
    if(ok==1) cout<<"Ciclu negativ!";
    else for(int i=2;i<=n;i++) cout<<d[i]<<" ";
    return 0;
}