English 中文(简体)
Algorithm, 用于喷洒气球所需的最小arrow数
原标题:Algorithm for minimum number of arrows required to pop lined-up balloons
最佳回答

页: 1 你与<条码>球标/代码”相关的所有其他内容与<条码>箭/代码”的价值实际上无关。 因此,这不能正确。 应当有某种条件确定你是否需要新arrow。

第二,通过分类输入清单,你失去信息。 也就是说,<代码>1 2 3 4 5和5 4 2 1将得出相同结果,但从实例来看,很明显,这两个投入的结果应当有所不同。

还有一个问题,即你超高标准balloon[j]。 如果你们有输入<代码>2 1 5 4 3<>/code>,那么你将销毁 lo首版(和其他几个数值)中的数值5。 没有理由change。 投入清单。

Approach

The idea is to check in each iteration whether you can match the balloon s height with a previous balloon that is one unit higher. At the same time keep track of how many balloons you have for each height you encounter. If there is a match with a previous balloon that is one unit higher, then remove that higher balloon. In all cases increment the counter for the current height, so to account for the current balloon.

At the end, count the number of balloons that are still there.

执行:

def calculate(balloons):
    d = { height: 0 for height in balloons }
    for height in balloons:
        if d.get(height + 1, 0):
            d[height + 1] -= 1
        d[height] += 1
    
    return sum(d.values())

# main code
n = int(input())
balloons = list(map(int, input().split()))
print(calculate(balloons))

所有的卡蒂测试都通过。

问题回答

这里的解决办法涉及维持一个字典({日):这一高度的arrow名单};它或许可以优化,但可以发挥作用:

def calculate(balloons):
    new_arrow = 0
    heights = {}
    for height in balloons:
        if not (arrows_list := heights.get(height)):
            # There s no arrow traveling at this height, we need to shoot a new one
            new_arrow += 1
            height -= 1
            if height:
                # If the arrow that popped the last balloon is still above ground, log it at the new height
                heights.setdefault(height, []).append(new_arrow)
        else:
            # No need for a new arrow, we ll just decrease the height of one
            arrow = arrows_list.pop()
            height -= 1
            if height:
                heights.setdefault(height, []).append(arrow)
    return new_arrow
                
                
print(calculate([2, 1, 5, 4, 3]))           # 2
print(calculate([4, 3, 5, 4, 3, 2, 2]))     # 2
print(calculate([1, 2, 3, 4, 5, 6]))        # 6

很显然,必须使用一只arrow子来排出最高的气球,而该箭不会击中左边的任何气球。 (如果最高高度有一个以上的气球,所有气球都必须按左对右的顺序单独穿透。) 这还可能把一些气球带走到最高气球的右边。 现在,在剩余的气球中,一个排位最高。 出于同样的理由,必须使用一只arrow子去除该气球,直至所有气球被击落。

因此,我们可以击落最大的气球,把该气球和所有气球的高度降为零,以防箭击中其世系。 直到所有气球都处于零高位之前,才再次出现这种情况。

下面是鲁比实施的法典。 在作解释后,我将作此规定,可视为假装,我预计可以轻易改装成“灰色”。

def pop_em_all(balloon_heights)
  heights = balloon_heights.dup
  shots = []
  loop do
    highest_left = highest_balloon_left(heights)
    break if heights[highest_left] == 0
    shots << highest_left
    pop_with_shot(heights, highest_left)
  end
  shots
end
def highest_balloon_left(heights)
  heights.each_index.max_by { |i| heights[i] }
end
def pop_with_shot(heights, highest_left)
  current_height = heights[highest_left]
  (highest_left..(heights.size - 1)).each do |balloon|
    if heights[balloon] == current_height
      heights[balloon] = 0
      current_height -= 1
    end
  end
end

让我们尝试。

pop_em_all [5, 4, 3, 2, 1]
  #=> [0]
pop_em_all [2, 1, 5, 4, 3]
  #=> [2, 0]
pop_em_all [2, 1, 5, 5, 4]
  #=> [2, 3, 0]
pop_em_all [2, 1, 5, 4, 3, 6, 1, 7, 3]
  #=> [7, 5, 2, 8, 0, 6]

主要方法,pop_em_all, 最初产生一份balloon_h 8,/code>, 称为hels。 这样做是为了避免在计算过程中修改<代码> 气球_hals


首先考虑求助器方法highest_balloon_left。 这只是确定余下的气球中哪一个是最高的,气球按其阵列指数确定。 例如,如果

heights = [2, 1, 5, 4, 3]

之后

highest_balloon_left(heights)
  #=> 2

如下文所示:

heights = [2, 1, 0, 0, 0]

......

highest_balloon_left(heights)
  #=> 0

从而成为<条码>[0、0、0、0、0、0],标志着我们已经结束。

helss = [2, 1, 5, 3]

highest_balloon_left(heights)
  #=> 2

之后,我们会发现

heights = [2, 1, 0, 5, 3]

决定

highest_balloon_left(heights)
  #=> 3

鉴于所针对的气球(h Salas),目标为pop_with_shotshalas[i] to 0 per balloon i

如果halas = [2,1,5,4, 3]hightest_left = 2,这将修改helss

[2, 1, 0, 0, 0]

The variable shots holds an array, initially empty, that will hold the balloon targeted by each arrow shot (the indices of heights and balloon_heights). At the end the size of this array will equal the minimum number of arrays required to shoot down all the balloons.

At each step the highest balloon i is identified and targeted, i is appended to shots and heights[j] is set to zero for every balloon j that is shot down by that arrow. The procedure is repeated until height[i] equals zero for all balloons i, ...... we are finished, with shots containing the targeted balloons, in order, with the size of that array equal to the minimum number of arrows required to dispatch all the balloons.





相关问题
How to add/merge several Big O s into one

If I have an algorithm which is comprised of (let s say) three sub-algorithms, all with different O() characteristics, e.g.: algorithm A: O(n) algorithm B: O(log(n)) algorithm C: O(n log(n)) How do ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Enumerating All Minimal Directed Cycles Of A Directed Graph

I have a directed graph and my problem is to enumerate all the minimal (cycles that cannot be constructed as the union of other cycles) directed cycles of this graph. This is different from what the ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...