基於鄰接表和優先級隊列的Dijkstra算法實現

/*基於鄰接表和優先級隊列的Dijkstra算法實現
 * */
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

class Node {
	int value;
	int num;

	public Node(int value, int num) {
		super();
		this.value = value;
		this.num = num;
	}
}

class NodeComparator implements Comparator<Node> {

	@Override
	public int compare(Node o1, Node o2) {
		if (o1.value > o2.value)
			return 1;
		else if (o1.value < o2.value)
			return -1;
		else {
			if (o1.num < o2.num)
				return -1;
			else if (o1.num > o2.num)
				return 1;
		}
		return 0;
	}
}

public class DijkstraALPQ {
	static final int MAX = 1 << 20;

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int m = scanner.nextInt();
		int[] first = new int[n];// first[u]保存節點u的第一條邊的編號
		int[] u = new int[m];// u[i]第i條邊的起點編號
		int[] v = new int[m];
		int[] w = new int[m];
		int[] next = new int[m];// next[e]表示編號爲e的邊的下一條邊
		int[] d = new int[n];// d[i]表示節點0到節點i的最短距離
		int[] vis = new int[n];
		int[] fa = new int[n];
		Arrays.fill(first, -1);// 初始化表頭
		for (int e = 0; e < m; e++) {
			u[e] = scanner.nextInt();
			v[e] = scanner.nextInt();
			w[e] = scanner.nextInt();
			next[e] = first[u[e]];// 插入鏈表
			first[u[e]] = e;
		}
		Arrays.fill(d, MAX);
		d[0] = 0;
		PriorityQueue<Node> q = new PriorityQueue<Node>(n, new NodeComparator());
		q.offer(new Node(d[0], 0));
		while (q.size() > 0) {
			Node node = q.poll();
			int x = node.num;
			if (vis[x] == 1)
				continue;
			vis[x] = 1;
			for (int e = first[x]; e != -1; e = next[e]) {
				if (d[v[e]] > d[x] + w[e]) {
					d[v[e]] = d[x] + w[e];
					fa[v[e]] = x;// 保留父節點
				}
				q.offer(new Node(d[v[e]], v[e]));
			}
		}
		for (int i = 0; i < n; i++) {
			if (i == 0) {
				System.out.println(0);
				continue;
			} else {
				System.out.printf("%d<-", i);
				int t = fa[i];
				while (t > 0) {
					System.out.printf("%d<-", t);
					t = fa[t];
				}
			}
			System.out.println(0 + "  the minmum length is " + d[i]);
		}
	}
}

輸入:
6
11
0 1 20
0 2 60
0 4 10
0 5 65
1 2 30
1 3 70
2 3 40
3 4 35
4 5 20
5 2 40
5 3 80
輸出:
0
1<-0  the minmum length is 20
2<-1<-0  the minmum length is 50
3<-1<-0  the minmum length is 90
4<-0  the minmum length is 10
5<-4<-0  the minmum length is 30

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章