Pagini recente » Cod sursa (job #685667) | Cod sursa (job #89037) | Cod sursa (job #2911703) | Cod sursa (job #1046151) | Cod sursa (job #3275318)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int oo = 2e9;
int n, m;
vector <vector<pair<int, int>>> graph;
vector <int> d, cnt;
queue <int> q;
void init() {
graph = vector<vector<pair<int, int>>> (n + 1);
d = vector <int> (n + 1, oo);
cnt = vector <int> (n + 1);
}
void read() {
fin >> n >> m;
init();
int x, y, dist;
for(int i = 1; i <= m; i ++) {
fin >> x >> y >> dist;
graph[x].push_back({y, dist});
}
}
bool bellmanford(int startNode) {
d[startNode] = 0;
q.push(startNode);
while(!q.empty()) {
int node = q.front();
q.pop();
if(cnt[node] >= n - 1)
return false;
else
cnt[node] ++;
for(const auto& neighbour : graph[node]) {
int otherNode = neighbour.first;
int otherDist = neighbour.second;
if(otherDist + d[node] < d[otherNode]) {
d[otherNode] = otherDist + d[node];
q.push(otherNode);
}
}
}
return true;
}
int main() {
read();
if(bellmanford(1)) {
for(int i = 2; i <= n; ++i)
fout << d[i] << " ";
}
else fout << "Ciclu negativ!";
}