题目
A. Thanos Sort
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Thanos sort is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.
Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort?
*Infinity Gauntlet required.
Input
The first line of input contains a single number n (1≤n≤16) — the size of the array. n is guaranteed to be a power of 2.
The second line of input contains n space-separated integers ai (1≤ai≤100) — the elements of the array.
Output
Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order.
Examples
input
4
1 2 2 4
output
4
input
8
11 12 1 2 13 14 3 4
output
2
input
4
7 6 5 4
output
1
Note
In the first example the array is already sorted, so no finger snaps are required.
In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you’ll have to snap your fingers twice to get to a 2-element sorted array.
In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction.
题目理解
这道题提供了一个未处理的序列,长度为2的多次幂,最长为16,通过零次或多次去除前半段或后半段来获得一个增序的序列,返回此时序列的长度。
解题思路
采用递归的思想,从首位数开始,当遇到不是增序的数时,将序列分成前后两段再进行判断,直到获取一个增序序列,返回此序列长度。最终结果为返回序列长度的最大值。
代码如下(python)
def run(num, l):
flag = 0
for i in range(1, num):
if l[i] < l[i-1]:
flag = 1
cntl = run(num>>1, l[0:num>>1])
cntr = run(num>>1, l[num>>1:num])
cnt = max(cntl, cntr)
return cnt
if flag == 0:
return num
a = int(input().strip())
b = map(int, input().strip().split())
b = list(b)
ans = run(a, b)
print(ans)
代码解析
b = map(int, input().strip().split())
b = list(b)
这一步有点繁琐了,可以更加便捷的去获取想要的列表,比如:
b = [int(_) for _ in input().strip().split()]