# Cod sursa(job #2631012)

Utilizator Data 28 iunie 2020 15:41:00 Algoritmul Bellman-Ford 35 cpp-64 done Arhiva educationala 1.22 kb
``````#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define all(a) (a).begin(), (a).end()
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#define sz() size()
#define fr first
#define sc second
#define int long long
#define mp make_pair
#define rc(s) return cout<<s,0
#define rcc(s) cout<<s,exit(0)
using namespace std;

const int inf = 1e9;
const int nmax = 50005;

int n,m,dist[nmax];

struct edge{
int s,d,w;
};

vector<edge>edges;

int32_t main(){
ios_base::sync_with_stdio(false);cin.tie(0);cerr.tie(0);cout.tie(0);
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
cin >> n >> m;
for(int i=1;i<=m;i++){
int x,y,z;
cin >> x >> y >> z;
edges.push_back({x,y,z});
}
for(int i=2;i<=n;i++) dist[i] = inf;
for(int i=1;i<=n;i++){
for(auto it : edges){
if(dist[it.s] + it.w < dist[it.d]){
if(i == n){
rc("Ciclu negativ!");
}
dist[it.d] = dist[it.s] + it.w;
}
}
}
for(int i=2;i<=n;i++) cout << dist[i] << ' ';
}

``````