求解最短路径Bellman_Ford 算法优化版——结合队列

来源:互联网 发布:淘宝拍卖的房子利弊 编辑:程序博客网 时间:2024/06/07 13:45
import java.util.*;public class Main {static Scanner in  = new Scanner(System.in);static int INF = 99999999;    static int[] dis = new int[100];    static int[] bck= new int[100];    static int[] v = new int[100];    static int[] u= new int[100];    static int[] w = new int[100];    static int[] first = new int[100];    static int[] next = new int[100];static int[] bool = new int[100];static int n,m,k;//使用first和next数组来实现链表public static void main(String[] args) {while(in.hasNext()){Queue<Integer> que = new LinkedList<>();Arrays.fill(bool, 0);n = in.nextInt();m = in.nextInt();   for (int i = 1; i <= n; i++) {dis[i]=INF;first[i]=-1;}    dis[1]=0;for (int i = 1; i <= m; i++) {u[i]=in.nextInt();v[i]=in.nextInt();w[i]=in.nextInt();//实现链表的关键代码,手写过程即可明白next[i]=first[u[i]];first[u[i]]=i;}//1入队que.add(1);bool[1]=0;while(que.size()!=0){k=first[que.peek()];//获取要处理队首顶点while(k!=-1){if(dis[v[k]]>dis[u[k]]+w[k]){dis[v[k]]=dis[u[k]]+w[k];if(bool[v[k]]==0){que.add(v[k]);bool[v[k]]=1;}}   k=next[k];//移动链表指针} bool[que.peek()]=0;//以后可能再次用到  que.poll();//出队  }for (int i = 1; i <= n; i++) {System.out.print(dis[i]+" ");} }  }}//结果示例//5 7//1 2 2//1 5 10//2 3 3//2 5 7 //3 4 4//4 5 5//5 3 6//0 2 5 9 9 

原创粉丝点击