# Cod sursa(job #2176446)

Utilizator Data 17 martie 2018 14:02:51 Algoritmul Bellman-Ford 70 cpp done Arhiva educationala 1.42 kb
``````#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#define NMAX 50010
#define INF (1<<30)
using namespace std;

typedef pair<int, int> int_pair;

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

bool bellmanford(int start, int N) {
queue<int> Q;
Q.push(start);
in_queue[start] = true;
cnt[start] = 1;

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

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

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));
}

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

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

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

return 0;
}
``````