Pagini recente » Cod sursa (job #336077) | Cod sursa (job #917909) | Cod sursa (job #2612277) | Cod sursa (job #1267307) | Cod sursa (job #3272256)
#include <vector>
#include <iostream>
#include <climits>
#include <fstream>
#include <queue>
using namespace std;
vector<int> bellman(const vector<vector<pair<int, int>>>& graph, int n, int start)
{
vector<int> dist(n + 1, INT_MAX);
vector<int> pred(n + 1, -1);
vector<bool> visited(n + 1, false);
queue<int> q;
dist[start] = 0;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int node = q.front();
q.pop();
visited[node] = false;
for (auto [neigh, cost] : graph[node]) {
if (dist[node] != INT_MAX && dist[node] + cost < dist[neigh]) {
dist[neigh] = dist[node] + cost;
if (!visited[neigh]) {
q.push(neigh);
visited[neigh] = true;
}
}
}
}
return dist;
}
int main()
{
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
fin >> n >> m;
vector<vector<pair<int, int>>> graph(n + 1);
for (int i = 0; i < m; i++) {
int a, b, c;
fin >> a >> b >> c;
graph[a].emplace_back(b, c);
}
vector<int> result = bellman(graph, n, 1);
if (!result.empty()) {
for (int i = 2; i <= n; i++) {
fout << result[i] << ' ';
}
}
return 0;
}