Pagini recente » Cod sursa (job #41510) | Cod sursa (job #1227549) | Cod sursa (job #895073) | Cod sursa (job #3267625) | Cod sursa (job #3134096)
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>
#include <climits>
using namespace std;
#define MAXN 50010
#define INF 1000000000
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector<pair<int, int>> G[MAXN];
pair<int, int> aux;
priority_queue<pair<int, int>> PQ;
int viz[MAXN], dist[MAXN], n, m, x, y, c, nod;
int main()
{
f >> n >> m;
for (int i = 1; i <= m; i++) {
f >> x >> y >> c;
G[x].push_back(make_pair(y, c));
}
for (int i = 2; i <= n; i++)
dist[i] = INT_MAX;
dist[1] = 0;
PQ.push({0, 1});
// O(nmlog(m))
while (PQ.size()) {
auto aux = PQ.top();
PQ.pop();
int nod = aux.second;
viz[nod]++;
if (viz[nod] > m) {
g << "Ciclu negativ!";
return 0;
}
for (auto it:G[nod]) {
if (dist[nod] + it.second < dist[it.first]) {
dist[it.first] = dist[nod] + it.second;
PQ.push({-dist[it.first], it.first});
}
}
}
for (int i = 2; i <= n; ++i)
g << dist[i] << ' ';
return 0;
}