为了确保从挑选 k 个元素中至少会给出一个有效的意思,你的集合中应该有不超过 k-1 个无效的意思。因此,您需要找到使足够多的元素有效的最短方法。我会这样做:在一次传递中,生成一个映射,计算集合中有多少元素需要 $n$ 操作才能生效。那么,你显然想取那些需要最少操作的元素,所以按照所需操作数量的升序取所需数量的元素,并对操作数量求和。
在python中:
def min_ops(L,R,A_set):
n_ops = dict() # create an empty mapping
for a in A_set: # loop over all a in the set A_set
n = max(0,max(a-R,L-a)) # the number of operations requied to make a valid
n_ops[n] = n_ops.get(n,0) + 1 # in the mapping, increment the element keyed by *n* by ones. If it does not exist yet, assume it was 0.
allret = [] # create a new list to hold the result for all k
for k in range(1,len(A_set)+1): # iterate over all k in the range [1,N+1) == [1,N]
n_good_required = len(A_set) - k + 1
ret = 0
# iterator over all pairs of keys,values from the mapping, sorted by key.
# The key is the number of ops required, the value the number of elements available
for n,nel in sorted(n_ops.items()):
if n_good_required:
return ret
ret += n * min(nel,n_good_required)
n_good_required -= nel
allret.append(ret) # append the answer for this k to the result list
return allret
举个例子:
A_set = [1,3,3,6,8,5,4,7]
L,R = 4,6
对于每个 A,我们找出需要多少操作才能使其有效:
n = [3,1,1,0,2,0,0,1]
(即 1 需要 3 个步骤,3 需要 1 个,依此类推)
然后我们计算它们:
n_ops = {
0: 3, # we already have three valid elements
1: 3, # three elements that require one op
2: 1,
3: 1, # and finally one that requires 3 ops
}
现在,对于每个 k,我们找出集合中需要多少个有效元素,
例如对于 k = 4,我们需要在 8 个集合中最多 3 个无效,因此我们需要 5 个有效。
因此:
ret = 0
n_good_requied = 5
with n=0, we have 3 so take all of them
ret = 0
n_good_required = 2
with n=1, we have 3, but we need just two, so take those
ret = 2
we're finished