Java优先级队列需要帮助
我正在这里处理旅行推销员问题,但我的 p 队列没有运行,它只是简单地获取最后添加的项目。我想知道是否有人可以帮助我找出错误。这是我的 Node 类(添加到队列中的节点):
import java.util.*;
public class Node implements Comparable< Node >{
//level of node
int level;
//stores path of node
ArrayList< Integer > path = new ArrayList< Integer >();
//bound of node
int bound;
/** Over-rides compareTo for priority queue handling
* @return int desired sorting value
*/
public int compareTo(Node aNode)
{
if (this.bound<aNode.bound)
{
return 1;
}
if (this.bound>aNode.bound)
{
return -1;
}
else
{
return 0;
}
}
}
这是 p 队列实现:
PriorityQueue< Node > theQ = new PriorityQueue< Node >();
该算法实现正确,p 队列根本没有将最低界限作为头。我什至反转了compareTo的返回,对p队列输出没有影响(对我来说,队列没有排序。我浪费了几个小时试图弄清楚它,还询问了一些同学(没有人能辨别出问题)在这里拍摄一下,看看是否有人知道为什么队列会这样。
I am working on a traveling salesman problem here and my p-queue isn't operating it is simply taking the last item added. I was wonder if anyone could help me figure out the error. here is my Node class (nodes which are added to the queue):
import java.util.*;
public class Node implements Comparable< Node >{
//level of node
int level;
//stores path of node
ArrayList< Integer > path = new ArrayList< Integer >();
//bound of node
int bound;
/** Over-rides compareTo for priority queue handling
* @return int desired sorting value
*/
public int compareTo(Node aNode)
{
if (this.bound<aNode.bound)
{
return 1;
}
if (this.bound>aNode.bound)
{
return -1;
}
else
{
return 0;
}
}
}
and here is the p-queue implementation:
PriorityQueue< Node > theQ = new PriorityQueue< Node >();
The algorithm is implemented correctly the p-queue simply is not putting the lowest bound as the head. I even reversed the the returns on the compareTo with no effect on the p-queue output (signifying to me that the queue is not sorting. I have wasted hours trying to figure it out and also asking some classmates (no-one can discern the problem) taking a shot here to see if anyone knows why the queue is acting like this..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的代码对我来说工作得很好。
我怀疑您正在做的是更改单个对象的绑定值并重复添加它,为您提供一个充满同一对象的队列(对它有很多引用),当然它具有您设置的单个(最后一个)值。
输出:
Your code works perfectly fine for me.
What I suspect you're doing is changing the the
bound
value of a single object and repeatedly adding it, giving you a queue full of the same object (lots of references to it) which of course has the single (last) value you set it to.Output:
确保您正在迭代 PriorityQueue使用 Queue 接口提供的方法,前任。
remove
将元素从顶部弹出。在伪代码中:如果您尝试迭代 for-each 循环或 PriorityQueue.iterator:
或者,如果您不想销毁/删除 PriorityQueue 中的元素以按顺序迭代,您可以使用,如文档所示,
Make sure you are iterating through the PriorityQueue by using the methods provided by the Queue interface, ex.
remove
to pop an element off the top. In pseudo code:If you are trying to iterate through a for-each loop or PriorityQueue.iterator:
Alternatively, if you don't want to destroy/remove elements from your PriorityQueue to iterate in order, you could use, as the documentation suggests,