Pagini recente » Cod sursa (job #3197106) | Cod sursa (job #1671883) | Cod sursa (job #2196737)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
const int MAX = 50001, INF = (1 << 30);
vector<pair<int, int> > adj[MAX];
int n, m, d[MAX], p[MAX], ap[MAX];
int bellman(int s) {
queue<int> q;
for(int i = 1; i <= n; ++i) {
d[i] = INF;
}
d[s] = 0;
q.push(s);
while(!q.empty()) {
int u = q.front();
q.pop();
++ap[u];
if(ap[u] == n) {
return 0;
}
for(auto it: adj[u]) {
int v = it.first;
int w = it.second;
if(d[v] > d[u] + w) {
d[v] = d[u] + w;
p[v] = u;
q.push(v);
}
}
}
return 1;
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; ++i) {
int u, v, w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
}
if(bellman(1) == 0) {
cout << "Ciclu negativ!";
} else {
for(int i = 2; i <= n; ++i) {
cout << d[i] << ' ';
}
}
return 0;
}