Pagini recente » Cod sursa (job #2069166) | Cod sursa (job #1425066) | Cod sursa (job #2669853) | Cod sursa (job #2933745) | Cod sursa (job #2297447)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
struct Edge {
int x, y;
long long c;
};
int main() {
int n, m;
in >> n >> m;
vector<vector<pair<int, long long>>> g(n + 1);
vector<Edge> e(m);
for(int i = 0; i < m; i ++) {
int x, y, c;
in >> x >> y >> c;
g[x].push_back({y, c});
e[i] = {x, y, c};
}
vector<long long> dist(n + 1, INT_MAX);
vector<bool> inqueue(n + 1, 0);
vector<int> cnt(n + 1, 0);
dist[1] = 0;
queue<int> q;
q.push(1);
inqueue[1] = 1;
cnt[1] = 1;
while(q.size() ) {
int node = q.front();
inqueue[node] = 0;
q.pop();
for(auto it : g[node])
if(dist[node] < dist[it.first] - it.second) {
dist[it.first] = dist[node] + it.second;
if(!inqueue[it.first]) {
q.push(it.first);
cnt[it.first] ++;
}
if(cnt[it.first] > n) {
out << "Ciclu negativ!";
return 0;
}
}
}
for(int i = 2; i <= n; i ++)
out << dist[i] << " ";
return 0;
}