给定H []和B []的两个数组,分别由N和M个整数组成,分别表示孔和球的直径。使M个球在具有N个孔的倾斜表面上从A滚动到B ,每个孔的深度不同,如下图所示:
该任务是考虑以下因素,以释放的球的顺序找到每个球的最终位置:
- 如果球的直径小于或等于孔的直径,则球将掉入孔中。
- 如果i个球落入一个孔H i中,它将充满。
- 如果孔已满,则不再有球落入其中。
- 当且仅当球未掉入任何一个孔中时,球才会从A到达B。
- 如果球在孔P i中,则其位置为i 。如果球到达最低点B,则将其位置设为0 。
例子:
Input: H[] = {21, 3, 6}, B[] = {20, 15, 5, 7, 10, 4, 2, 1, 3, 6, 8}
Output: 1 0 3 0 0 3 3 2 2 0 0
Explanation:
Ball of diameter 20 will fall into the hole H1 and the hole H1 will become full.
Balls with diameter 15, 7 and 10 will reach bottom, since the hole H1 is full and diameters of holes H2 and H3 are less than the diameters of the balls.
Balls with diameters 5, 4 and 2 will fall into the hole H3.
Ball with diameter 1 will fall into the hole H2 since the hole H3 is already full.
Ball with diameter 3 will fall into hole H2.
Balls with diameters 6, and 8 will reach the bottom point B.
The position of ball 20 is 1 because it is in hole H1.
Positions of ball 15, 7, 10, 3, 6, and 8 are 0 because they reached the bottom point B.
Therefore, the balls with diameter 5, 4 and 2 are in the 3rd hole H3, the ball with diameter 1 and 3 are in the 2nd hole H2.
Input: H[] = {20, 15, 10, 5, 25}, B[] = {5, 10, 15, 20, 25, 30, 4, 9, 14, 19}
Output: 5 5 5 5 5 0 4 3 2 1
方法:请按照以下步骤解决问题:
- 初始化的大小为N的阵列位置[]存储每个球的最终位置和大小为N的一个阵列深度[]存储每个孔的容量。
- 使用变量i在范围[1,N]上进行迭代,并将hole [i]的初始深度[i]设置为i + 1 。
- 使用变量i遍历数组ball []并执行以下操作:
- 以相反的顺序使用变量j遍历数组hole []。
- 检查孔的直径是否大于或等于球的直径,即,孔[j]≥球[i] ,并且如果该孔未满,即深度[j]> 0 ,则将孔放置球在孔由位置[]阵列中追加J + 1和由1递减所述孔的深度和中断环路的进行。
- 如果球不适合任何孔(已到达坡度的末端),则将0附加到position []数组中。
- 以相反的顺序使用变量j遍历数组hole []。
- 完成上述步骤后,打印存储在数组position []中的值作为结果。
下面是上述方法的实现:
Python3
# Python program for the above approach
# Function to find and print the final
# position of balls
def ballPositionFinder(diameter_of_holes,
diameter_of_balls):
max_hole_limit_counter = []
position_value = []
# Stores the positions of balls
ball_positions = []
# Determine the maximum balls a hole
# can store and note the position
# of holes in position_value
for i in range(1, len(diameter_of_holes)+1):
max_hole_limit_counter.append(i)
position_value.append(i)
# Iterate over all possible holes
# for every ball released
for i in range(0, len(diameter_of_balls)):
for j in range(1, len(diameter_of_holes)+1):
# Place ball in hole if it fits
# in and if hole is not full
if (diameter_of_holes[-j] >= diameter_of_balls[i]) and (
max_hole_limit_counter[-j] != 0):
ball_positions.append(position_value[-j])
max_hole_limit_counter[-j] -= 1
break
# If ball has reached at end B
if j == len(diameter_of_holes):
ball_positions.append(0)
break
return ball_positions
# Driver Code
if __name__ == "__main__":
diameter_of_holes = [21, 3, 6]
diameter_of_balls = [20, 15, 5, 7, 10, 4,
2, 1, 3, 6, 8]
# Function Call
output = ballPositionFinder(diameter_of_holes,
diameter_of_balls)
print(*output, sep =' ')
1 0 3 0 0 3 3 2 2 0 0
时间复杂度: O(N * M)
辅助空间: O(N)