Pagini recente » Cod sursa (job #34749) | Cod sursa (job #2686730) | Cod sursa (job #2132644) | Cod sursa (job #1091284) | Cod sursa (job #2453702)
#include <fstream>
#include <queue>
#include <vector>
#define inf 1000000000
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
queue<int> q;
long n, m, cost[50010], times[50010];
vector<pair<int, int> > G[50010];
int main() {
f >> n >> m;
for(int i = 1; i <= m; i++) {
int a, b, c;
f >> a >> b >> c;
G[a].push_back({b, c});
}
cost[1] = 0;
for(int i = 2; i <= n; i++)
cost[i] = inf;
q.push(1);
while(!q.empty()) {
int a = q.front();
q.pop();
times[a]++;
if(times[a] > n) {
g << "Ciclu negativ!";
return 0;
}
for(int i = 0; i < G[a].size(); i++) {
int b = G[a][i].first;
int c = G[a][i].second;
if(cost[b] > cost[a] + c) {
cost[b] = cost[a] + c;
q.push(b);
}
}
}
for(int i = 2; i <= n; i++)
g << cost[i] << ' ';
}