Pagini recente » Cod sursa (job #1936832) | Cod sursa (job #2624375) | Cod sursa (job #2963044) | Cod sursa (job #823520) | Cod sursa (job #2696853)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
const int N_MAX = 100005;
const int INF = 1e9;
std :: vector<std :: pair <int, int> > graph[N_MAX];
std :: queue <int> q;
int dist[N_MAX], cicle[N_MAX];
bool vis[N_MAX];
int n, m;
int main() {
std::ifstream fin("bellamnford.in");
std::ofstream fout("bellmanford.out");
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int a, b, c;
fin >> a >> b >> c;
graph[a].emplace_back(b, c);
}
for (int i = 1; i <= n; ++i) {
dist[i] = INF;
}
dist[1] = 0;
vis[1] = true;
q.push(1);
while (!q.empty()) {
int node = q.front();
q.pop();
vis[node] = true;
for (auto i : graph[node]) {
int next = i.first;
int cost = i.second;
if (dist[node] + cost < dist[next]) {
dist[next] = dist[node] + cost;
if (!vis[next]) {
q.push(next);
cicle[next]++;
if (cicle[next] >= n) {
fout << "Ciclu negativ!";
return 0;
}
}
}
}
}
for (int i = 2; i <= n; ++i) {
fout << dist[i] << " ";
}
return 0;
}