数字游戏
时间限制:2 s
内存限制:256 MB
给定一个序列n 正数 a1, a2, ……, an. 只要有不同的数字,就执行以下操作:选择一个最大的数字并从中减去最小的数字。 将执行多少操作?输入输入的第一行包含数字n(1 <n<1000)。下一行包含个数字 ai (1 < ai < 10^9)。输出打印一个数字,操作的次数。
例子
标准输入
2
1 1
标准输出
0
标准输入
3
9 6 3
标准输出
3
标准输入
6
1000000000 1000000000 1000000000 1000000000 1000000000 1
标准输出
4999999995
你题目的解答代码如下:
n = int(input())
a = list(map(int,input().split()))
count = 0
while True:
maxv = max(a)
minv = min(a)
if maxv==minv:
break
if maxv % minv==0:
count += maxv//minv-1
a[a.index(maxv)] = minv
else:
count += maxv//minv
a[a.index(maxv)] = maxv % minv
print(count)
如有帮助,望采纳!谢谢!
按照你的描述来:
# 优先队列
class Queue:
# 定义根节点
def __init__(self, size):
self.front = 0
self.tail = 0
self.List = [None] * size
# 判断是否对空
def isEmpty(self):
return self.front == self.tail
# 判断是否队满
def isFull(self):
return self.tail == len(self.List)
# 将数据按照大小入队
def enqueue(self, array):
new_array = sorted(array, reverse=True)
for i in range(len(new_array)):
if self.isFull() is False:
self.List[i] = new_array[i]
self.tail += 1
else:
print("超出给定长度")
return -1
# 进行计算
def func(self):
new_list = self.List
number = 0
# 无不同的数
if self.List[0] == self.List[-1]:
return 0
else:
while max(new_list) != min(new_list):
max_index = new_list.index(max(new_list))
new_list[max_index] = max(new_list) - min(new_list)
number += 1
return number
if __name__ == '__main__':
the_size = input("请输入n:")
the_array = list(eval(i) for i in input("请输入序列(用空格隔开):").split(' '))
queue = Queue(eval(the_size))
queue.enqueue(the_array)
print(queue.func())
按照你的描述每一次都处理的话,最大数字和最小数字差小的时候,2s内可以完成,但大的时候(你的最后一个例子)2秒就弄不完(时间复杂度很高, 我暂时想不到有效降低时间的方法了
你的问题是什么意思啊?是选择最大值,然后删掉最小值还是什么?
n = int(input())
a = list(map(int,input().split()))
count = 0
while True:
a.sort()
maxv = a[-1]
minv = a[0]
if maxv==minv:
break
idx = n - 1
while idx > 0:
if a[idx] == a[0]:
break
if a[idx] % a[0] == 0:
count += a[idx] // a[0] - 1
a[idx] = a[0]
else:
count += a[idx] // a[0]
a[idx] = a[idx] % a[0]
idx = idx - 1
print(count)