双栈实现Queue:最小Push/Pop操作次数计算的疑问
双栈实现队列的最小操作次数争议
使用最优算法用两个栈S1和S2实现队列Q。对空队列依次执行以下操作:Enqueue(A)、Enqueue(B)、Enqueue(C)、Dequeue()、Enqueue(E)、Enqueue(F)、Dequeue()、Dequeue()、Dequeue()
执行上述操作所需的最小Push操作次数为x,最小Pop操作次数为y,求x*y的值?
这是一道作业题,给出的答案为90,但我认为正确答案应为56。
原算法(计算结果为90)
Enqueue: Push the new element onto inbox Dequeue: If outbox is empty, refill it by popping each element from inbox and pushing it onto outbox Pop and return the top element from outbox
改进后的算法(计算结果为56)
Updated_Dequeue: If outbox is empty: Refill it by popping each element from inbox and pushing it onto outbox except the last one. Pop and return the top(which is the last one) element from inbox else: Pop and return the top element from outbox
该改进每次从inbox向outbox转移元素执行Dequeue时,可节省一次Pop和一次Push操作。
我认为该改进不会改变算法的渐近复杂度,但题目明确询问最小Push和Pop操作次数,正确答案应该是56,对吗?
谢谢!
内容的提问来源于stack exchange,提问作者ray an
相关产品推荐
相关产品推荐

