基于邻接表和优先级队列的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值