Pagini recente » Cod sursa (job #1853017) | Cod sursa (job #1770672) | Cod sursa (job #2219930) | Cod sursa (job #2191371) | Cod sursa (job #3004804)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int DIM = 50010;
int n, m, x, y, c;
int dist[DIM], inQueue[DIM];
vector<pair<int, int>> l[DIM];
deque<int> q;
bool visited[DIM];
bool bellmanFord(int start) {
dist[start] = 0;
q.push_back(start);
while (!q.empty()) {
int node = q.front();
q.pop_front();
visited[node] = false;
for (auto adjElem : l[node]) {
int adjNode = adjElem.first;
int adjDist = adjElem.second;
if (dist[adjNode] > dist[node] + adjDist) {
dist[adjNode] = dist[node] + adjDist;
if (!visited[adjNode]) {
inQueue[adjNode]++;
if (inQueue[adjNode] > n) {
fout << "Ciclu negativ!";
return false;
}
visited[adjNode] = true;
q.push_back(adjNode);
}
}
}
}
return true;
}
int main() {
fin >> n >> m;
for (int i = 1; i <= m; i++) {
fin >> x >> y >> c;
l[x].push_back(make_pair(y, c));
}
for (int i = 1; i <= n; i++)
dist[i] = INT_MAX;
if (bellmanFord(1)) {
for (int i = 2; i <= n; i++)
fout << dist[i] << ' ';
}
return 0;
}