# Cod sursa(job #2176431)

Utilizator Data 17 martie 2018 13:24:44 Algoritmul Bellman-Ford 70 cpp done Arhiva educationala 1.42 kb
``````#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
#define NMAX 50010
using namespace std;

typedef pair<int, int> int_pair;

vector<int_pair> G[NMAX];
int dist[NMAX], level[NMAX];
bool in_queue[NMAX];

bool bellmanford(int start, int N) {
memset(level, -1, sizeof(level));

queue<int> Q;
level[start] = 0;
Q.push(start);
in_queue[start] = true;

while (!Q.empty()) {
int nod = Q.front();
Q.pop();
in_queue[nod] = false;

for (auto &edge : G[nod]) {
if (level[edge.first] == -1 || dist[edge.first] > dist[nod] + edge.second) {
dist[edge.first] = dist[nod] + edge.second;
level[edge.first] = level[nod] + 1;
if (level[edge.first] == N) return false;
if (!in_queue[edge.first]) {
Q.push(edge.first);
in_queue[edge.first] = true;
}
}
}
}

return true;
}

int main() {
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);

int N, M, x, y, c, i;
cin >> N >> M;
for (i = 0; i < M; i++) {
cin >> x >> y >> c;
G[x].push_back(make_pair(y, c));
}

if (!bellmanford(1, N)) {
cout << "Ciclu negativ!";
return 0;
}

for (i = 2; i <= N; i++) {
cout << dist[i] << ' ';
}

return 0;
}
``````