Pagini recente » Cod sursa (job #1010665) | Cod sursa (job #3351068) | Cod sursa (job #637607) | Cod sursa (job #3327732) | Cod sursa (job #3329706)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define INF 1e9
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
bool bellmanFord(int start, vector<vector<pair<int, int>>> &la, vector<int> &d, int N) {
vector<int> tata(N + 1, 0), lung(N + 1, 0);
vector<bool> inQueue(N + 1, false);
d.assign(N + 1, INF);
queue<int> q;
d[start] = 0;
q.push(start);
inQueue[start] = true;
while (!q.empty()) {
int crt = q.front();
q.pop();
inQueue[crt] = false;
for (auto& vecin : la[crt]) {
int cost = vecin.first;
int nod = vecin.second;
if (d[crt] < INF && d[crt] + cost < d[nod]) {
d[nod] = d[crt] + cost;
tata[nod] = crt;
if (inQueue[nod] == false) {
q.push(nod);
inQueue[nod] = true;
}
lung[nod] = lung[crt] + 1;
if (lung[nod] > N - 1) {
return true;
}
}
}
}
return false;
}
int main() {
int N, M;
fin >> N >> M;
vector<vector<pair<int, int>>> la(N + 1);
for (int i = 0; i < M; i++) {
int x, y, w;
fin >> x >> y >> w;
la[x].push_back({w, y});
}
vector<int> d;
bool hasCycle = bellmanFord(1, la, d, N);
if (hasCycle) {
fout << "Ciclu negativ!" << endl;
} else {
for (int i = 2; i <= N; i++) {
fout << d[i] << ' ';
}
fout << endl;
}
}