堆栈寿命

时间:2014-06-28 08:09:48

标签: data-structures stack

问题:

设S是一个大小为n> = 1的堆栈。从空堆栈开始,假设我们按顺序推送前n个自然数,然后执行n个pop操作。

假设Push和Pop操作各占X秒,并且在一个这样的堆栈操作结束和下一个操作开始之间经过Y秒。

对于m> = 1,将m的堆栈生命定义为从Push(m)结束到从S中删除m的pop操作开始所经过的时间。元素的平均堆栈寿命这个堆栈是

(A) n(X+ Y)
(B) 3Y + 2X
(C) n(X + Y)-X
(D) Y + 2X

问题来自Link

我的方法:

For n elements Push takes X time, hence for m elements Push takes m/n*X    
For n elements Pop takes X time, hence for m elements Push takes m/n*X    
Interval Time is m/n*Y
Stack Life = End of Push(m) to start of Pop(m) = Interval Time = m/n*Y
Average Stack Life = (m/n*Y) / m = Y/n

没有一个答案是匹配的。 请指导我实现目标的正确方法。

2 个答案:

答案 0 :(得分:6)

这是我的方法:

Stack lifetime of nth element -> Y
For (n-1)th -> 2X+2Y + stack lifetime of nth element = 2X + 3Y
For (n-2)th -> 2X+2Y + stack lifetime of (n-1)th element = 4X + 5Y
..
..
For 1st -> 2(n-1)X + (2n-1)Y
对于n = 1到n

Sum of all life spans= (Σ 2(n-1)X) + (Σ (2n-1)Y)

按上述总和从1到n计算总和,你会得到:

Sum = n(n(X+Y)-X)
Therefore Average = Sum/n = n(X+Y)-X .  Hence Option (c)

此问题已在此处提出:http://geeksquiz.com/data-structures-stack-question-7/

答案 1 :(得分:2)

Here is mine: 
PUSH Operations:
1. After Push(m) i.e., from Push(m+1) till Push(n) --> there are (n-m) Push operations(ops) => (n-m)X ops

2. After Push(m) to the Push(m+1) --> there is one Y ops ==> till Push(n) ==> (n-m)Y ops

--> Time taken to finish Push(n) after Push(m) ==> (n-m)(X+Y)

POP Operations:
1. After Push(n) to the Pop(n) --> there is one Y ops ==> till Pop(m) ==> (n-m+1)Y ops (this is one extra Y after Pop(m+1) and reach Pop(m))

2. From Push(n) till Push(m+1) --> there are (n-m) Push operations(ops) => (n-m)X ops

--> Time taken to finish Pop(m+1) from Push(n) ==> (n-m)(X+Y)+Y

Overall Time for any arbitrary m, T(m) ==> 2(n-m)(X+Y) + Y

To obtain the average: Sum(T(m)), for all m: 1->n
==> Sum{ 2(n-m)(X+Y) + Y } over m: 1->n
==> 2(X+Y){(n-1) + (n-2) + .... + 0 }+ (Y + Y ... n-times)
==> 2(n(n-1)/2)(X+Y) + nY = n(n-1)(X+Y) + nY
Average: Above sum / n
==> (n-1)(X+Y) + Y = n(X+Y)-X