Pagini recente » Cod sursa (job #2824174) | Cod sursa (job #493569) | Cod sursa (job #511615) | Cod sursa (job #472634) | Cod sursa (job #2843259)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
const int INF = 50e6;
vector<pair<int, int>> graf[50005];
int dist[50005];
int f[50005];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y, d;
cin >> x >> y >> d;
graf[x].push_back({ y, d });
}
for (int i = 2; i <= n; i++) {
dist[i] = INF;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
q.push({ 0, 1 });
while (!q.empty()) {
int now = q.top().second;
q.pop();
for (auto i : graf[now]) {
if (dist[now] + i.second < dist[i.first]) {
dist[i.first] = dist[now] + i.second;
f[i.first]++;
if (f[i.first] > m) {
cout << "Ciclu negativ!";
return -0;
}
q.push({ dist[i.first], i.first });
}
}
}
for (int i = 2; i <= n; i++) {
cout << dist[i] << ' ';
}
return 0;
}