Java 优先队列PriorityQueue排序Pair

本文详细解释了如何使用lambda表达式重定义`PriorityQueue`的排序逻辑,从默认的值比较到根据需要实现的大于或小于操作。特别关注了如何在Java中调整`Pair`对象的优先级比较规则。

用lambda定义pair排序逻辑

 PriorityQueue<Pair<Integer,Integer>> q = 
            new PriorityQueue<Pair<Integer,Integer>>((a,b) -> a.getValue() - b.getValue());

这里(a,b) -> a.getValue() - b.getValue() 如果的逻辑是 返回值>0 则a大,否则b大

优先队列默认是小顶堆,最小元素在堆顶

如果要改变默认排序方式:

PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);

迪杰斯特拉算法是一种用于计算图中一个节点到其他所有节点最短路径的算法,适用于图中所有边权为非负数的情况。优先队列(通常使用最小堆实现)可以有效优化迪杰斯特拉算法的性能。 ### 结合使用方法 迪杰斯特拉算法的每一轮都需要找一个未被访问且距离起点最近的点来进行操作,传统方法需要遍历距离数组,比较耗时。而优先队列以距离排序,队首为距离最小元素。每次更新一个点的距离时,将当前点与距离组合成 `pair` 放入优先队列,每次取出队首,就能知道距离起始点最近的点,大大优化计算时间[^2]。 ### 实现原理 迪杰斯特拉算法从源点出发,不断扩展到其他节点并更新最短路径。使用优先队列时,优先队列用于存储待处理的节点及其到源点的距离。初始时,将源点及其距离(为 0)放入优先队列。每次从优先队列中取出距离源点最近的节点,将其作为当前处理的节点,然后遍历该节点的所有邻接节点,计算通过当前节点到达邻接节点的距离,如果该距离比邻接节点当前记录的距离小,则更新邻接节点的距离,并将邻接节点及其新距离放入优先队列。重复此过程,直到优先队列为空[^1][^2][^4]。 ### 代码实现 #### Python 实现 ```python import heapq def dijkstra(graph, start): distances = {node: float('inf') for node in graph} distances[start] = 0 priority_queue = [(0, start)] while priority_queue: current_distance, current_node = heapq.heappop(priority_queue) if current_distance > distances[current_node]: continue for neighbor, weight in graph[current_node].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return distances # 示例图 graph = { 'A': {'B': 1, 'C': 4}, 'B': {'A': 1, 'C': 2, 'D': 5}, 'C': {'A': 4, 'B': 2, 'D': 1}, 'D': {'B': 5, 'C': 1} } start_node = 'A' result = dijkstra(graph, start_node) print(result) ``` #### Java 实现 ```java import java.util.*; class Edge { int source; int destination; int weight; public Edge(int source, int destination, int weight) { this.source = source; this.destination = destination; this.weight = weight; } } class Node implements Comparable<Node> { int node; int distance; public Node(int node, int distance) { this.node = node; this.distance = distance; } @Override public int compareTo(Node other) { return Integer.compare(this.distance, other.distance); } } public class Dijkstra { public static Map<Integer, Integer> dijkstra(Map<Integer, List<Edge>> graph, int start) { Map<Integer, Integer> distances = new HashMap<>(); for (int node : graph.keySet()) { distances.put(node, Integer.MAX_VALUE); } distances.put(start, 0); PriorityQueue<Node> priorityQueue = new PriorityQueue<>(); priorityQueue.add(new Node(start, 0)); while (!priorityQueue.isEmpty()) { Node current = priorityQueue.poll(); int currentNode = current.node; int currentDistance = current.distance; if (currentDistance > distances.get(currentNode)) { continue; } if (graph.containsKey(currentNode)) { for (Edge edge : graph.get(currentNode)) { int neighbor = edge.destination; int weight = edge.weight; int distance = currentDistance + weight; if (distance < distances.get(neighbor)) { distances.put(neighbor, distance); priorityQueue.add(new Node(neighbor, distance)); } } } } return distances; } public static void main(String[] args) { Map<Integer, List<Edge>> graph = new HashMap<>(); // 初始化图 List<Edge> edges1 = new ArrayList<>(); edges1.add(new Edge(0, 1, 1)); edges1.add(new Edge(0, 2, 4)); graph.put(0, edges1); List<Edge> edges2 = new ArrayList<>(); edges2.add(new Edge(1, 0, 1)); edges2.add(new Edge(1, 2, 2)); edges2.add(new Edge(1, 3, 5)); graph.put(1, edges2); List<Edge> edges3 = new ArrayList<>(); edges3.add(new Edge(2, 0, 4)); edges3.add(new Edge(2, 1, 2)); edges3.add(new Edge(2, 3, 1)); graph.put(2, edges3); List<Edge> edges4 = new ArrayList<>(); edges4.add(new Edge(3, 1, 5)); edges4.add(new Edge(3, 2, 1)); graph.put(3, edges4); int startNode = 0; Map<Integer, Integer> result = dijkstra(graph, startNode); System.out.println(result); } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值