Bellman-Ford算法
//Bellman-Ford算法(含有负权的最短路径问题) #include <stdio.h> #define MAXM 100 #define MAXN 10 const int INF = 1<<20; int u[MAXM], v[MAXM], w[MAXM]; int d[MAXN]; int Bellman_Ford(int v0, int n, int m){ int i, k; for(i=0; i<n; i++) d[i] = INF; d[v0] = 0; for(k=0; k<n-1; k++){ for(i=0; i<m; i++){ int x = u[i], y = v[i]; if(d[x] < INF && d[x]+w[i]<d[y]) d[y] = d[x]+w[i]; } } for(i=0; i<m; i++){ //检查是否存在负环 int x = u[i], y = v[i]; if(d[x] < INF && d[y] > d[x] + w[i]) return 0; //如果存在,返回假 } return 1; } int main(){ //freopen("d:\\my.txt", "r", stdin); int n, m, i; scanf("%d %d", &n, &m); for(i=0; i<m; i++) scanf("%d %d %d", &u[i], &v[i], &w[i]); if(Bellman_Ford(0, n, m)) printf("%d\n", d[n-1]); else printf("ERROR!\n"); return 0; }
较好的一篇介绍Bellman-Ford算法的文章
http://www.360doc.com/content/11/0915/16/7511080_148495650.shtml