Codeforces Round 672 (Div. 2) A. Cubes Sorting

131 阅读2分钟

题目链接

题目详情

Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent — cubes.

For completing the chamber Wheatley needs nn cubes. i-th cube has a volume aia_i.

Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each i>1,ai1aii>1, a_i−1≤a_i must hold.

To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any i>1 you can exchange cubes on positions i−1 and i.

But there is a problem: Wheatley is very impatient. If Wheatley needs more than n(n1)/21n⋅(n−1)/2−1 exchange operations, he won't do this boring work.

Wheatly wants to know: can cubes be sorted under this conditions?

Input

Each test contains multiple test cases.

The first line contains one positive integer t(1t1000)t (1≤t≤1000), denoting the number of test cases. Description of the test cases follows.

The first line of each test case contains one positive integer n(2n5104)n (2≤n≤5⋅10^4) — number of cubes.

The second line contains nn positive integers ai(1ai109)a_i (1≤a_i≤10^9) — volumes of cubes.

It is guaranteed that the sum of nn over all test cases does not exceed 105105.

Output

For each test case, print a word in a single line: "YES" (without quotation marks) if the cubes can be sorted and "NO" (without quotation marks) otherwise.

题目大意及解题思路

大意:
惠特利决定试着做一个试验箱。为了完成测试室,惠特利需要n个立方体。第i个立方体有一个体积ai。惠特利必须以这样一种方式放置立方体,即它们将按体积按不递减的顺序排序。从形式上讲,对于每一个i>1,ai−1≤ai必须成立。为了实现他的目标,惠特利可以交换两个相邻的立方体。这意味着,对于任何i>1,你都可以在i−1和i位置交换立方体。但有一个问题:惠特利非常不耐烦。如果惠特利需要的交换操作超过n·(n−1)/2-1,他不会做这项无聊的工作。惠特利想知道:在这种条件下,立方体可以排序吗?
解题思路:
其实这道题是一道思维题(加一些基础数学知识)。给我们n个数,让我们判断能否经过不超过n(n1)/21n⋅(n−1)/2−1 次交换相邻两个数使整个数组非递减。当我们看到n(n1)/21n⋅(n−1)/2−1 时,如果对数学很敏感就会发现他是1+2+...+n-1的和-1。其次,我们考虑极端情况,整个数组严格递减(5,4,3,2,1)时,我们需要交换的次数最多而且次数刚好为n(n1)/2n⋅(n−1)/2 ,而且不满足题目要求,满足题目要求的次数一定会小于等于n(n1)/21n⋅(n−1)/2−1 。所以我们只需要判断该数组是不是严格递减的即可。

AC代码

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;

int main()
{   
    int n,a[50010];

    int t;
    cin >> t;
    while (t--)
    {
        cin >> n;
        for (int i = 0; i < n; i++)
        {
            cin >> a[i];
        }
        bool flag = false;
        for (int i = 0; i < n - 1; i++)
        {
            if (a[i] <= a[i + 1])
            {
                flag = true;
                break;
            }
        }
        if (flag)
        {
            puts("YES");
        }
        else
        {
            puts("NO");
        }
    }
    return 0;
}