bellman-ford
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
const int INF = 1000000;
vector <pair<int, int> > edges[6001];
int dist[501];
bool isCycle;
int main() {
int N, M, from, to, cost;
scanf("%d %d", &N, &M);
for(int i=0; i<M; i++){
scanf("%d %d %d", &from, &to, &cost);
edges[from].push_back(make_pair(to, cost));
}
fill_n(dist, N+1, INF);
dist[1] = 0;
for(int i=1; i<=N; i++){
for(int j=1; j<=N; j++){
for(int k=0; k<edges[j].size(); k++){
int next = edges[j][k].first;
int cost = edges[j][k].second;
if(dist[j] != INF && dist[next] > dist[j] + cost){
dist[next] = dist[j] + cost;
if(i==N){
isCycle=true;
}
}
}
}
}
if(isCycle){
puts("-1");
}
else{
for(int i=2; i<=N; i++) {
if(dist[i] == INF) puts("-1");
else printf("%d\n", dist[i]);
}
}
return 0;
}