OD 算法题 B卷【数字序列比大小】
文章目录
- 数字序列比大小
数字序列比大小
- A、B两人每人一个整数数组,长度相等,数组元素是随机的;
- 两人各自挑选出一个元素(弹出),比较大小,赢的得一分,输的减去一分,否则各自分值都不变,用过的数字需要丢弃;
- B每取一个元素都明示,求在过程中,A可能赢B的最大分值;
输入描述:
第一行输入n,表示数组长度
第二行输入A的数组arr1
第三行输入B的数组arr2
输出描述:
求A赢B时的最大分值
示例1
输入:
3
4 8 10
3 6 4
输出:
3
示例2
输入:
4
3 6 2 10
2 5 7 11
输出:
3
思路:
- 田忌赛马问题,下等马(注定输的)对比别人的上等马;
- 对两个数组升序排序;
- b_arr持续弹出第一个值,a_arr中取能赢b_arr的最小值(最次的马能赢就行);
- a_arr能找到这样的值,则 a_score加1, b_score 减1;
- 若找不到,说A不能再赢B了,说明此时A的分值已达到峰值,直接break并输出a_score即可;
python:
n = int(input().strip())
a_arr = list(map(int, input().strip().split()))
b_arr = list(map(int, input().strip().split()))# 1. 升序排序
a_arr.sort()
b_arr.sort()# 分值初始化
a_score = b_score = 0flag = True # 表示A能赢B
while flag and b_arr:flag = Falseb_val = b_arr.pop(0)i = 0# 取保证A赢的最小元素while i < len(a_arr) and a_arr[i] <= b_val: # 只有大于才算赢i += 1# 在有效范围内找到A能赢的值if i < len(arr_a):flag = Truea_arr.pop(i)a_score += 1b_score -= 1print(a_score)
其他方案
def num_queue_compare(nums1, nums2):# 对A和B的数字序列进行排序nums1.sort()nums2.sort()# 创建一个队列,用于存储B的数字序列queue = nums2[:]# 记录A和B之间的最大分数ans = 0# 遍历A的数字序列for num in nums1:# 如果A的当前数字小于等于B队列的最小数字(队列的第一个元素),A不能赢if num < queue[0]:ans -= 1 # A输了,B得分,A扣分queue.pop() # B用掉当前最大的数字elif (num == queue[0]):queue.pop() # B用掉当前最大的数字else:ans += 1 # A赢了,A得分queue.pop(0) # B用掉当前最小的数字# 返回A可能赢B的最大分数return ans# 获取输入
n = int(input())
nums1 = list(map(int, input().split()))
nums2 = list(map(int, input().split()))# 输出结果
print(num_queue_compare(nums1, nums2))