Pagini recente » Cod sursa (job #3317651) | Cod sursa (job #3313135) | Cod sursa (job #1342966) | Cod sursa (job #274320) | Cod sursa (job #3357969)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int MAXN = 50001;
const long long INF = 1e18;
int N, M;
vector<pair<int, int>> graph[MAXN];
long long dist[MAXN];
bool inQueue[MAXN];
int cnt[MAXN];
bool bellmanford() {
queue<int> q;
for (int i = 1; i <= N; ++i) {
dist[i] = INF;
inQueue[i] = false;
cnt[i] = 0;
}
dist[1] = 0;
q.push(1);
inQueue[1] = true;
while (!q.empty()) {
int node = q.front();
q.pop();
inQueue[node] = false;
for (auto &edge : graph[node]) {
int neighbor = edge.first;
int cost = edge.second;
if (dist[node] + cost < dist[neighbor]) {
dist[neighbor] = dist[node] + cost;
if (!inQueue[neighbor]) {
q.push(neighbor);
inQueue[neighbor] = true;
cnt[neighbor]++;
if (cnt[neighbor] >= N) {
return true;
}
}
}
}
}
return false;
}
int main() {
fin >> N >> M;
for (int i = 0; i < M; ++i) {
int x, y, c;
fin >> x >> y >> c;
graph[x].push_back({y, c});
}
if (bellmanford()) {
fout << "Ciclu negativ!";
} else {
for (int i = 2; i <= N; ++i) {
fout << dist[i];
if (i < N) fout << " ";
}
}
fin.close();
fout.close();
return 0;
}