Java优先级队列
我将如何使用java内置的优先级队列来读入和排序图的顶点,最终删除每次迭代的最小边?
How would I use the priority queue built into java to read in and sort vertices of a graph, ultimately removing the minimum edge at each iteration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,为优先级队列创建一个比较器:
这是来自我编写的最短路径算法。 mDistances 是从源到顶点的距离。您可以修改比较器来比较您喜欢的方式。
来自比较器的文档:“比较其两个参数的顺序。当第一个参数小于、等于或大于第二个参数时,返回负整数、零或正整数。”
完整文档位于:http://download.oracle .com/javase/1.5.0/docs/api/java/util/Comparator.html
其次,将项目添加到优先级队列中。我通常使用包含顶点对象的数组构建一个图,每个对象包含其相邻顶点的列表。因此,就我而言,我只是将索引添加到优先级队列中来表示顶点。然后比较器可以包含对顶点执行任何操作的逻辑。 PriorityQueue.add() 添加项目。
第三,使用比较器实例化优先级队列:
第四,调用 PriorityQueue.poll() 提取堆顶项目。您的比较器用于确定堆顶部的项目。
First, create a comparator for the priority queue:
This is from a shortest path algorithm I wrote. mDistances is the distances from source to a vertex. You can modify the comparator to compare how you like.
From the documentation for Comparator: "Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second."
Complete documentation here: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Comparator.html
Second, add items to the priority queue. I usually build a graph with an array containing vertex objects, each object containing a list of its adjacent vertices. So in my case I just add indices to the priority queue to represent vertices. The comparator can then contain logic to do whatever with the vertices. PriorityQueue.add() adds items.
Third, instantiate the priority queue with the comparator:
Fourth, call PriorityQueue.poll() to extract the top item on the heap. Your comparator is used to determine what item is on the top of the heap.