Pagini recente » Cod sursa (job #779355) | Cod sursa (job #953307) | Cod sursa (job #658089) | Cod sursa (job #321973) | Cod sursa (job #1379557)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int kNMax = 50010, Inf = 9999999;
int n, dist[kNMax], contor[kNMax], ok;
bool in_q[kNMax];
queue<int> Queue;
vector<pair<int,int> > G[kNMax];
void Citire() {
ifstream in("bellmanford.in");
int m, x, y, c;
in >> n >> m;
for (int i = 1; i <= m; ++i) {
in >> x >> y >> c;
G[x].push_back(make_pair(y, c));
}
in.close();
}
void Initializare() {
for (int i = 1; i <= n; ++i)
dist[i] = Inf;
ok = 1;
}
void BellmanFord(int start) {
Queue.push(start);
dist[start] = 0;
contor[start] = 1;
while (!Queue.empty()) {
int nod = Queue.front();
Queue.pop();
in_q[nod] = 0;
for (int i = 0; i < G[nod].size(); ++i) {
int vecin = G[nod][i].first;
int cost = G[nod][i].second;
if (dist[vecin] > dist[nod] + cost) {
dist[vecin] = dist[nod] + cost;
if (!in_q[vecin]) {
in_q[vecin] = 1;
++contor[vecin];
Queue.push(vecin);
}
}
if (contor[vecin] >= n) {
ok = 0;
return;
}
}
}
}
void Solve() {
Initializare();
BellmanFord(1);
}
void Afisare() {
ofstream out("bellmanford.out");
if (!ok)
out << "Ciclu negativ!";
else
for (int i = 2; i <= n; ++i)
out << dist[i] << ' ';
out << '\n';
out.close();
}
int main () {
Citire();
Solve();
Afisare();
return 0;
}