http://www.spoj.com/problems/SAM/的贪心方法论证

时间:2013-06-07 14:12:27

标签: algorithm

我正在解决这个问题:http://www.spoj.com/status/SAM,iiit/
我以某种方式得出了解决方案,但我仍然不能用数学证明它。

问题陈述是什么:

There are 'n' toys (1<=n<=10^5) on a shelf.A child is on the floor.He demands toys in
a sequence to play with , specified by 'p' (1<=p<=5*10^5).His mother gives him a toy
from the shelf if the child demanded a toy which is not on floor.At a time only
'k'(1<=k<=n) toys can be there on floor.So mother when giving toy from shelf can pick a
toy from floor and put it back to shelf if she wants.
So we have to minimize total number of times mother picks toys from shelf.

我的解决方案:
(a)变量和功能:

Keep a set of toys on floor and a variable ans(initially 0),which stores the answer.
Also next[],next[i] tells when will toy number 'i' come next in the demand sequence,
ie. index of its next occurrence in demand sequence.
update next[x] updates next[x] to store the next index of its occurrence in  demand 
sequence.If there is no further occurrence next[x]=MAX_INTEGER;

(b)算法

Following are the cases:
1.If child demands a 'x' toy from shelf:
  increment ans
  If there are less than k elements then:
       add the element to the set
       update next[x]
  If there are k elements:
      remove the element from set whose value of next[] is largest
      add element 'x' to set 
      update next[x]
2.If child demands toy from floor say toy 'x':
  update next[x]
ans is the final answer.

现在我无法证明为什么这种贪婪的方法在数学上是正确的。

1 个答案:

答案 0 :(得分:2)

这实际上是一个缓存问题 - 地板是缓存,自我是主存。

您提供的算法是最佳的,因为它只是clairvoyant algorithm。它是一种经典算法,您可以在很多操作系统资源上找到它。

网上也有几个,例如herehere

相关问题