前言:从上一篇文章我们可以看出,我们的每次去松弛,都会遍历所有的边,此时我们可以对其进行优化,只遍历那些相临接的那些点。
思路:
我们可以通过队列记录那些我们相邻的点。程序一直到队列为空时停止。这需要我们先开始一个初始化点。还有我们需要为我们的输入边设置一个邻接表来数据存储,或是使用邻接矩阵来存储。
好啦 直接上代码。
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