CodeForce题解——Thanos Sort

题目链接

CodeForce网站。http://codeforces.com/problemset/problem/1145/A

我的小破站。http://47.110.135.197/problem.php?id=5113

题面

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.

输入

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 containsn space-separated integers ai (1 ≤ ai ≤ 100) — the elements of the array.

输出

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.

样例输入

4
1 2 2 4

样例输出

4

题目分析

首先,CF题目最难是全英文,要读懂英文的意思。

说真Thanos这个单词真的不认识,百度了一下,灭霸的意思。这个霸气。

本题的意思是,某种排序,排序方法是这样: remove the first or the second half of the items。哦,就是删除前半部分或者后半部分。果然是灭霸风格,打个响指,人口减半。OK,排序什么时候结束呢?The elements of the array have to be sorted in non-decreasing order. 哦,只要满足数组中的元素是有序的,而且是非降序。哦,不容易,题目终于看懂了。

数学知识

应该没有。

数据范围分析

1 ≤ n ≤ 16,1 ≤ ai ≤ 100。果然是水题。

考点

1)如何判断数组是有序的。本题的数据量少,可以自己写个子函数来判断。最简单的方法是使用STL中的algorithm函数is_sorted()来判断。

2)如何实现灭霸排序。分析一下题目要求,我们只需要求出最大的非降序子数组长度。因此只需要采用双指针方法来判断即可,也就是一个 left 和 right 构成的数组,判断从 left 到 right 的子数组是否是有序的即可。因此可以使用递归来实现这个判断算法。哪么算法的复杂度应该就是O(logn)。

坑点

应该没有吧。我想英文理解能力不算是坑点。

AC代码

//1145A Thanos Sort 灭霸排序
//http://codeforces.com/problemset/problem/1145/A
#include <cstdio>
#include <algorithm>

const int MAXN = 20;
int data[MAXN] = {};

bool mycmp(int x, int y) {
    return x<y;
}

//灭霸排序,返回
int thanos_sort(int left, int right) {
    if (true == std::is_sorted(data+left, data+right, mycmp)) {
        return right-left;
    } else {
        int l = (right-left)/2;
        return std::max(thanos_sort(left, right-l), thanos_sort(left+l, right));
    }
}

int main() {
    int n;
    scanf("%d", &n);

    int i;
    for (i=0; i<n; i++) {
        scanf("%d", &data[i]);
    }

    int ans = thanos_sort(0, n);

    printf("%d\n", ans);

    return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力的老周

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值