Pagini recente » Cod sursa (job #3249991) | Cod sursa (job #873071) | Cod sursa (job #1797364) | Cod sursa (job #2710318) | Cod sursa (job #2981344)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
const int nMax = 50001;
vector<pair<int, int>> v[nMax];
int dist[nMax];
bool bellmanford(const int &nodStart, const int nrNoduri, const int nrMuchii) {
for (int i = 2; i <= nrNoduri; i++)
dist[i] = INT_MAX;
queue<int> q;
q.push(nodStart);
long long co = 0;
while (!q.empty()) {
const int nodCurent = q.front();
q.pop();
co++;
if (1LL * co >= 1LL * nrNoduri * nrMuchii)
return false;
for (auto &i: v[nodCurent]) {
const int &vecin = i.first;
const int &cost = i.second;
if (dist[nodCurent] + cost < dist[vecin]) {
dist[vecin] = dist[nodCurent] + cost;
q.push(vecin);
}
}
}
return true;
}
int main() {
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
fin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, cost;
fin >> a >> b >> cost;
v[a].emplace_back(b, cost);
}
if (bellmanford(1, n, m)) {
for (int i = 2; i <= n; i++)
fout << dist[i] << ' ';
} else {
fout << "Ciclu negativ!\n";
}
fin.close();
fout.close();
return 0;
}