[算法]路上的球

路上的球

题目地址

题目描述
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
5 5
1 4 5 6 8
2 3 4 6 9
Sample Output
29
题目解析
  1. 给两个数组,两个数组都是排好序的,数组的长度叫做桶的个数,其中每个数代表球的个数
  2. 我们要从一个数组去收集球,每当遇到两个数组中重复的部分,则可以选择更换数组去收集球
  3. 输出收集到的球的最大值

简而言之: 以相同的数字将两个数组划分成多段,求两个数组每段的值.对于每一段,在两个数组中选择一个大值,并将最大值求和

思路解析

由于数组是有序的,我们只需遍历数组1,和数组2,如果数组1的当前值比数组2的小,就将数组1向后移动一位,同时记录和,直到数组1和数组2的值相同,则选择和大的即可

注意: 数组遍历结束后仍需要额外统计一次

eg:

total = 0
1 4
2 3 4   
1 < 2+3 于是我们选择第二个数组,即total += (2+3)+4 

total = 9
5 6
6       
5>0,于是我们选择第一个数组,即 total += 5+6

total = 20
8
9
9>8,于是我们选择第二个数组 total += 9

total =29
代码实现

python

if __name__ == '__main__':
    for _ in range(int(input())):
        _ = input()
        arr1 = list(map(int, input().strip().split(" ")))
        arr2 = list(map(int, input().strip().split(" ")))
        i, j, total = 0, 0, 0
        sum1 = 0
        sum2 = 0
        while i < len(arr1) and j < len(arr2):  # 遍历
            if arr1[i] < arr2[j]:  # 如果数组1小于数组2
                sum1 += arr1[i] # 统计和
                i += 1 # i向后移动
            elif arr1[i] > arr2[j]:
                sum2 += arr2[j]
                j += 1
            else:# 数组1等于数组2
                total += max(sum1, sum2) + arr1[i] #将较大和加入total
                i, j = i + 1, j + 1 # 同时向后
                sum1, sum2 = 0, 0 # 和归零
        # 数组遍历结束后,还要统计一次剩余元素
        if i == len(arr1): # 若数组1到头了
            sum2 += sum(arr2[j:]) # 则把数组2的剩下元素加起来
        if j == len(arr2):
            sum1 += sum(arr1[i:])
        total += max(sum1, sum2)  # 比较大小,大的加入total
        print(total)
发布了71 篇原创文章 · 获赞 21 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_33935895/article/details/103328208