Pagini recente » Cod sursa (job #557752) | Cod sursa (job #3337342) | Cod sursa (job #874142) | Cod sursa (job #1402995) | Cod sursa (job #3336982)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
#define NMAX 50005
#define INF INT_MAX
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int N, M, cnt[NMAX], dist[NMAX];
vector<pair<int, int>> adj[NMAX];
queue<int> q;
bool in_queue[NMAX];
bool spfa(int t){
dist[t] = 0;
cnt[t] = 1;
q.push(t);
in_queue[t] = 1;
while(!q.empty()){
int curr = q.front();
q.pop();
in_queue[curr] = 0;
for(auto& x : adj[curr]){
if(dist[curr] != INF && dist[curr] + x.second < dist[x.first]){
dist[x.first] = dist[curr] + x.second;
if(!in_queue[x.first]){
q.push(x.first);
in_queue[x.first] = 1;
cnt[x.first]++;
if(cnt[x.first] >= N)
return 0;
}
}
}
}
return 1;
}
int main(){
f >> N >> M;
for(int i = 1; i <= M; i++){
int x, y, z;
f >> x >> y >> z;
adj[x].push_back({y, z});
}
for(int i = 1; i <= N; i++)
dist[i] = INF;
bool t = spfa(1);
if(!t)
g << "Ciclu negativ!";
else{
for(int i = 2; i <= N; i++)
g << dist[i] << ' ';
}
return 0;
}