codeforces-1145A-Thanos Sort(分治策略)

原题链接: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 4

output

4

input

8
11 12 1 2 13 14 3 4

output

2

input

4
7 6 5 4

output

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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值