Pagini recente » Cod sursa (job #524673) | Cod sursa (job #1965521) | Cod sursa (job #1187273) | Cod sursa (job #594504) | Cod sursa (job #2202557)
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50005
#define pb push_back
#define INF 1e9
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
class Node{
public:
int y, cost;
Node(int y, int cost):y{y}, cost{cost} {}
};
vector<Node> G[NMAX];
queue<int>q;
int n, m;
bool is_negative = false;
int dist[NMAX];
void read_data(int &n, int &m){
f >> n >> m;
for(int i = 1; i<=m; i++){
int x, y, cost;
f >> x >> y >> cost;
//g << x << y << cost << '\n'
G[x].pb(Node(y, cost));
}
}
void bellman_ford(int start){
int cnt_cycle[n + 1];
for(int i = 1; i<=n; i++){
dist[i] = INF;
cnt_cycle[i] = 0;
}
dist[start] = 0;
q.push(start);
while(!q.empty()){
int node = q.front();
q.pop();
for(const auto& vec : G[node]){
if(dist[node] + vec.cost < dist[vec.y]){
dist[vec.y] = dist[node] + vec.cost;
cnt_cycle[vec.y] ++;
if(cnt_cycle[vec.y] > n){
is_negative = true;
return;
}
else{
q.push(vec.y);
}
}
}
}
}
int main(){
read_data(n, m);
bellman_ford(1);
if(is_negative == true){
g << "Ciclu negativ!";
return 0;
}
for(int i = 2; i<=n; i++){
dist[i] != INF ? g << dist[i] << ' ' : g << 0 << ' ';
}
return 0;
}