【问题标题】:Stack Life Span堆栈寿命
【发布时间】:2014-08-19 08:06:52
【问题描述】:

问题:

令 S 为大小为 n >= 1 的堆栈。从空堆栈开始,假设我们按顺序压入前 n 个自然数,然后执行 n 个弹出操作。

假设 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

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

【问题讨论】:

  • 请在帖子中说明您的问题。

标签: data-structures stack


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    这是我的方法:

    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
    

    Sum of all life spans= (Σ 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)
    

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

    【讨论】:

      猜你喜欢
      • 2014-07-26
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 2015-09-17
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      相关资源
      最近更新 更多