Pagini recente » Cod sursa (job #1481029) | Cod sursa (job #884803) | Cod sursa (job #1785459) | Cod sursa (job #919628) | Cod sursa (job #2570261)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
const int INF = 1e9 + 5;
int main() {
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n, m;
in >> n >> m;
vector<vector<pair<int, int>>> g(n + 1);
for(int i = 1; i <= m; i ++) {
int x, y, c;
in >> x >> y >> c;
g[x].push_back({y, c});
}
vector<int> dist(n + 1, INF);
queue<int> q;
vector<bool> inq(n + 1, 0);
vector<int> cnt(n + 1, 0);
inq[1] = 1;
dist[1] = 0;
q.push(1);
while(q.size()) {
auto from = q.front();
q.pop();
inq[from] = 0;
for(auto it : g[from]) {
if(dist[it.first] > dist[from] + it.second) {
dist[it.first] = dist[from] + it.second;
if(!inq[it.first]) {
inq[it.first] = 1;
cnt[it.first] ++;
q.push(it.first);
if(cnt[it.first] >= n) {
out << "Ciclu negativ!";
return 0;
}
}
}
}
}
for(int i = 2; i <= n; i ++)
out << dist[i] << " ";
return 0;
}