最短路径之Ford之队列优化算法

前言:从上一篇文章我们可以看出,我们的每次去松弛,都会遍历所有的边,此时我们可以对其进行优化,只遍历那些相临接的那些点。


 

思路:

我们可以通过队列记录那些我们相邻的点。程序一直到队列为空时停止。这需要我们先开始一个初始化点。还有我们需要为我们的输入边设置一个邻接表来数据存储,或是使用邻接矩阵来存储。

 

好啦 直接上代码。

import java.util.Arrays;
import java.util.Scanner;
//5 7
//1 2 2
//1 5 10
//2 3 3
//2 5 7
//3 4 4
//4 5 5
//5 3 6
public class FordDeque {
	public static int inf = 999999;
	public static Node head;
	public static Node tail;
	static class Node{
		Node next;
		int data;
		public Node(int e){
			this.data = e;
		}
	}
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int m = scanner.nextInt();//顶点数
		int n = scanner.nextInt();//边的数量
		
	    int[] u = new int[n+1];
	    int[] v = new int[n+1];
	    int[] w = new int[n+1];
	    
	    int[] books = new int[m+1];
	    for(int i = 1 ; i <= m ; i++) {
	    	books[i] = 0;
	    }
	    books[1] = 1;
	    
	    int []dis = new int[m+1];
	    for(int i = 1 ; i <= m ; i++) {
	    	dis[i] = inf;
	    }
	    dis[1] = 0 ;
	    
	    head = new Node(1);
	    tail = new Node(1);
	    head.next = tail;
	    tail.next = null;
	    
	    int []first = new int[m+1];
	    Arrays.fill(first, -1);
	    int []next = new int[n+1];
	    Arrays.fill(next, -1);
	    
	    for(int i = 1 ; i <= n; i++) {
	    	u[i] = scanner.nextInt();
	    	v[i] = scanner.nextInt();
	    	w[i] = scanner.nextInt();
	    	next[i] = first[u[i]];
	    	first[u[i]] = i;
	    }
	    
	    while(head!=null) {
	    	int k = first[head.data];
	    	while(k!=-1) {
	    		if(dis[v[k]]>dis[u[k]]+w[k]) {
	    			dis[v[k]] = dis[u[k]]+w[k];
	    			if(books[v[k]]==0) {
	    				Node node1 = new Node(v[k]);
	    				tail.next = node1;
	    				node1.next = null;
	    				tail = node1;
	    				books[v[k]] = 1;
	    			}
	    		}
	    		k = next[k];
	    	}
	    	books[head.data] = 0;
    		head = head.next;
	    }
	    for(int i = 1 ; i <= m ; i++) {
	    	System.out.print(dis[i]+" ");
	    }
		scanner.close();
	}
}

Thanks

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值