路上的球
Description
There are two parallel roads, each containing N and M buckets, respectively. Each bucket may contain some balls. The buckets on both roads are kept in such a way that they are sorted according to the number of balls in them. Geek starts from the end of the road which has the bucket with a lower number of balls(i.e. if buckets are sorted in increasing order, then geek will start from the left side of the road). The geek can change the road only at the point of intersection(which means, buckets with the same number of balls on two roads). Now you need to help Geek to collect the maximum number of balls.
Input
The first line of input contains T denoting the number of test cases. The first line of each test case contains two integers N and M, denoting the number of buckets on road1 and road2 respectively. 2nd line of each test case contains N integers, number of balls in buckets on the first road. 3rd line of each test case contains M integers, number of balls in buckets on the second road.
Constraints:1<= T <= 1000,1<= N <= 10^3,1<= M <=10^3,0<= A[i],B[i]<=10^6
Output
For each test case output a single line containing the maximum possible balls that Geek can collect.
Sample Input 1
1
5 5
1 4 5 6 8
2 3 4 6 9
Sample Output 1
29
题目解析
给两个数组,两个数组都是排好序的,数组的长度叫做桶的个数,其中每个数代表球的个数
我们要从一个数组去收集球,每当遇到两个数组中重复的部分,则可以选择更换数组去收集球
输出收集到的球的最大值
简而言之: 以相同的数字将两个数组划分成多段,求两个数组每段的值.对于每一段,在两个数组中选择一个大值,并将最大值求和
思路解析
由于数组是有序的,我们只需遍历数组1,和数组2,如果数组1的当前值比数组2的小,就将数组1向后移动一位,同时记录和,直到数组1和数组2的值相同,则选择和大的即可
注意: 数组遍历结束后仍需要额外统计一次
参考
python
# 路上的球
# 两条路,路上分别有N和M个桶,桶里放着一定数量的球,从小到大排序,相同球数的地方可以换道,求能收集到的最大球数。
# 其实,就是两个数组,长度分别为M和N,数组的值为球数。
# 将数组分成多段,求两数组每段的值,每次取最大的作为最优解的一部分。
def max_ball(arr1, arr2):
i = j = result = 0
sum_arr1 = 0
sum_arr2 = 0
while i <len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
sum_arr1 += arr1[i]
i += 1
elif arr2[j] < arr1[i]:
sum_arr2 += arr2[j]
j += 1
else: # 相同,取最大
result += max(sum_arr1 + arr1[i], sum_arr2 + arr2[j])
i += 1
j += 1
sum_arr1 = sum_arr2 = 0
if i == len(arr1): # 统计最后剩下的元素
sum_arr2 += sum(arr2[j:])
if j == len(arr2):
sum_arr1 += sum(arr1[i:])
result += max(sum_arr1, sum_arr2)
return result
if __name__ == '__main__':
for _ in range(int(input())):
N, M = map(int, input().split())
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
print(max_ball(arr1, arr2))