Pagini recente » Cod sursa (job #9153) | Cod sursa (job #3162209) | Cod sursa (job #2378933) | Cod sursa (job #3137748) | Cod sursa (job #2176447)
#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], paths[NMAX];
bool in_queue[NMAX];
bool bellmanford(int start, int N) {
queue<int> Q;
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 (dist[edge.first] == INF || dist[edge.first] > dist[nod] + edge.second) {
dist[edge.first] = dist[nod] + edge.second;
paths[edge.first]++;
if (paths[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));
}
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;
}