原题链接:http://codeforces.com/contest/1145/problem/A
题目原文:
A. Thanos Sort
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard 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 nn (1≤n≤161≤n≤16) — the size of the array. nn is guaranteed to be a power of 2.
The second line of input contains nn space-separated integers aiai (1≤ai≤1001≤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 4output
4input
8 11 12 1 2 13 14 3 4output
2input
4 7 6 5 4output
1
题目大意:
给出一个thanos排序法,数组长度是2^n(n <= 16) ,如果数组无序,那么删除前一半或者后一半,直到数组有序。问最后有序长度。
解题思路 :
既然是删除前一半或后一半,那么前一半和后一半的答案是独立的,只有两部分都完全有序,答案才需要合并。使用分治思想递归求解。
AC代码:
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 20;
int thanos(const int arr[], const int &l, const int &r)
{
if (l == r) return 1;
int half = (r - l + 1) >> 1;
int m = half + l;
int ans1 = thanos(arr, l, m - 1);
int ans2 = thanos(arr, m, r);
if (arr[m] >= arr[m - 1] && ans1 == ans2 && ans1 == half) return ans1 + ans2;
else return max(ans1, ans2);
}
int main()
{
int arr[N];
int i, n;
while (scanf("%d", &n) != EOF)
{
for (i = 1; i <= n; i++)
{
scanf("%d", &arr[i]);
}
printf("%d\n", thanos(arr, 1, n));
}
return 0;
}