Data structures 堆栈寿命

Data structures 堆栈寿命,data-structures,stack,Data Structures,Stack,问题: 设我们是一个大小为n>=1的堆栈。从空堆栈开始,假设我们按顺序推送前n个自然数,然后执行n个pop操作 假设推送和弹出操作各花费X秒,在一个这样的堆栈操作结束和下一个操作开始之间经过Y秒 对于m>=1,将m的堆栈寿命定义为从推送结束(m)到从S中移除m的pop操作开始所经过的时间。此堆栈元素的平均堆栈寿命为 (A) n(X+ Y) (B) 3Y + 2X (C) n(X + Y)-X (D) Y + 2X 从这一点上提出的问题 我的做法: For n elements Push tak

问题:

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

假设推送和弹出操作各花费X秒,在一个这样的堆栈操作结束和下一个操作开始之间经过Y秒

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

(A) n(X+ Y)
(B) 3Y + 2X
(C) n(X + Y)-X
(D) Y + 2X
从这一点上提出的问题

我的做法:

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
没有一个答案是匹配的。 请指导我实现目标的正确方法。

以下是我的方法:

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
所有寿命的总和=(2(n-1)X)+(2n-1)Y)
对于n=1到n

通过上述从1到n的总和计算总和,您将得到:

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

这里有人问了这个问题:

请在帖子中说明您的问题。
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