简体   繁体   English

Prim的算法,使用优先级队列

[英]Prim's algorithm, using a priority queue

I'm trying to implement prim's algorithm, using a priority queue. 我正在尝试使用优先级队列来实现prim的算法。 When I call offer() method, it gives me a class cast exception, saying that vertex cannot be cast to comparable. 当我调用offer()方法时,它给了我一个类强制转换异常,表示顶点不能强制转换为可比对象。 Is there a workaround? 有解决方法吗?

public static Collection<Edge> prims(Graph g, int start) {
            ArrayList<Edge> mst = new ArrayList<Edge>();
            PriorityQueue<Vertex> vertices = new PriorityQueue<Vertex>();
            Vertex startVertex;

        for (Vertex vertex : g.getVertices()) {
            vertices.offer(vertex);
            if (vertex.getId() == start) {
                startVertex = vertex;
            }
        }

        if (!mst.isEmpty()) {
            return mst;
        }

        return null;
    }
}

Prims algorithm uses the weight of the edge to determine the best path. Prims算法使用边缘的权重来确定最佳路径。 Posting the vertex to the PriorityQueue will not work. 将顶点发布到PriorityQueue将不起作用。

I am guessing your Edge class will implement Comparable by comparing their lengths. 我猜测您的Edge类将通过比较它们的长度来实现Comparable

Yes: you need your Vertex method to implement Comparable<Vertex> . 是的:您需要使用Vertex方法来实现Comparable<Vertex>

Java's PriorityQueue is an implementation of a heap, which has log-time insertion, and log-time removal of the minimum element. Java的PriorityQueue是堆的实现,该堆具有日志时间插入和最小元素的日志时间删除。 But in order for that to be meaningful, you need to have a notion of minimum ; 但是,为了使之有意义,您需要具有最小的概念。 and that means you need whatever you put into a PriorityQueue to be Comparable , so that two elements in the heap can be compared. 这意味着您需要将放在PriorityQueue都设为Comparable ,以便可以比较堆中的两个元素。

The reason that non- Comparable elements can be inserted into a PriorityQueue is that you can also specify a Comparator in the constructor, rather than using Comparable elements. 可以将非Comparable元素插入PriorityQueue是,您还可以在构造函数中指定一个Comparator ,而不是使用Comparable元素。 So as an alternative, you could leave your Vertex class as it is, but use the appropriate constructor (which also requires you to specify an initial capacity): 因此,可以选择保留Vertex类,但使用适当的构造函数(这也需要您指定初始容量):

PriorityQueue<Vertex> vertices = new PriorityQueue<Vertex>(11,
    new Comparator<Vertex>() {
        //implement .compare() and .equals()
    });

The solution is to have your Vertex class implement Comparable , or to provide a Comparator to the priority queue when constructing it. 解决方案是让您的Vertex类实现Comparable ,或者在构造优先级队列时为优先级队列提供一个Comparator The Java collections framework needs a way to compare your vertices (after all you're putting them into a priority queue and priority implies the necessity of some ordering being present). Java集合框架需要一种比较顶点的方法(毕竟,将它们放入优先级队列中,并且优先级意味着必须存在一些排序)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM