# Cod sursa(job #2631017)

Utilizator Data 28 iunie 2020 15:51:36 Algoritmul Bellman-Ford 10 cpp-64 done Arhiva educationala 1.4 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];
vector<pair<int,int>>nod[nmax];
queue<int>Q;

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;
nod[x].push_back({y,z});
}
Q.push(1);
for(int i=2;i<=n;i++) dist[i] = inf;
for(int i=1;i<n;i++){
vector<int>tz;
while(Q.front()){
int x = Q.front();
for(auto it : nod[x]){
if(dist[x] + it.sc < dist[it.fr]){
dist[it.fr] = dist[x] + it.sc;
tz.push_back(it.fr);
}
}
Q.pop();
}
for(auto it : tz) Q.push(it);
}
if(Q.size()){
rc("Ciclu Negativ!");
}
for(int i=2;i<=n;i++) cout << dist[i] << ' ';
}

``````