Bellman-ford
The algorithm solves the single-source shortest path problem in general, and its edge can be negative. The Bellman-ford algorithm can determine if there is a negative ring in the graph and returns a Boolean value if there is a negative ring. Of course, the value of the shortest path is returned if there is no negative ring present.
#include <stdio.h>#include<string.h>#include<queue>#include<algorithm>using namespacestd;#defineINF 0x3f3f3f#defineN 11110intDis[n];intS,t,m,n;structpoint{intU,v,w;} P[n];voidBellman () {Dis[s]=0;///source point initialized to 0m = m<<1;///equivalent to M*2, because it's a non-graph. for(intI=1; i<n;i++)///do |v-1| times { intf =0; for(intj=0; j<m;j++) { if(DIS[P[J].U]>DIS[P[J].V]+P[J].W)///Slack Handling{dis[p[j].u]=dis[p[j].v]+P[J].W; F=1;///Slack Success Tag } } if(!f)///no slack on all sides, just jump out. Break; } printf ("%d\n", dis[t]==inf?-1:d is[t]);}intMain () { while(SCANF ("%d%d", &n,&m)! =EOF) {Fill (Dis,dis+N,inf); for(intI=0; i<m;i++) {scanf ("%d%d%d",&p[i].u,&p[i].v,&P[I].W); P[i+M].V =p[i].u; P[i+M].U =p[i].v; P[i+M].W =P[I].W; } scanf ("%d%d",&s,&t); Bellman (); } return 0;}
POJ 1874 Smooth Works continued