Codeforces Global Round 9 Problem C

题面

C. Element Extermination
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a of length n, which initially is a permutation of numbers from 1 to n. In one operation, you can choose an index i (1≤i<n) such that ai<ai+1, and remove either ai or ai+1 from the array (after the removal, the remaining parts are concatenated).

For example, if you have the array [1,3,2], you can choose i=1 (since a1=1<a2=3), then either remove a1 which gives the new array [3,2], or remove a2 which gives the new array [1,2].

Is it possible to make the length of this array equal to 1 with these operations?

Input
The first line contains a single integer t (1≤t≤2⋅104) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer n (2≤n≤3⋅105) — the length of the array.

The second line of each test case contains n integers a1, a2, ..., an (1≤ai≤n, ai are pairwise distinct) — elements of the array.

It is guaranteed that the sum of n over all test cases doesn't exceed 3⋅105.

Output
For each test case, output on a single line the word "YES" if it is possible to reduce the array to a single element using the aforementioned operation, or "NO" if it is impossible to do so.

Example
inputCopy
4
3
1 2 3
4
3 1 2 4
3
2 3 1
6
2 4 6 1 3 5
outputCopy
YES
YES
NO
YES

思路

意思就是给你一个数组,只要符合第i项小于第i+1项,那么我们可以去掉任意一项,那么我们这么考虑,我们找出比a1大的所有项,这么我们都可以去掉,那么关键就在于那些比a1小的项,这些项如果被去掉那么可能性是什么呢,就是那么在那些比a1大的项的前面,所以我们基于这样的思路,如果比a1小的所有项都可以被筛去,那么这个数组我们可以化为只有一个。这是一种思路,还有一种解题思路更为简洁,我们直接考虑a1和an的大小就好了,那么为什么这种想法是正确的呢?我们从两边开始考虑,如果我不去掉a1和an,那么这两个最终会被留下,那么怎么样,因为他们的关系,这个数组无法被减为1个,那么如果去掉呢,由题目意思,如果我们去掉左右两个点,在左端,我们得到的一定是一个更大的数字,同理右端只会更小,那么这样更加不满足我们的题意了。所以我们只需要比较左右两个点的大小关系就好了。

代码实现(第一种思路)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int n;
int main () {
    int t ;
    cin>>t;
    while (t--) {
        int cnt=0,tot=0,flag=0;
        cin>>n;
        int a[n]={0},smallnum[n]={0},pos[n]={0},can_remove[n]={0};
        for (int i=1;i<=n;i++) cin>>a[i];
        for (int i=2;i<=n;i++) {
            if (a[i]>a[1]) {
                pos[++cnt]=i;
                can_remove[i]=1;
            }
            if (a[i]<a[1]) smallnum[++tot]=i;
        }
        for (int i=1;i<=cnt;i++) 
         for (int j=2;j<=pos[i];j++) {
             if (a[j]<a[pos[i]]) can_remove[j]=1;
         }
        for (int i=1;i<=tot;i++) {
            if (!can_remove[smallnum[i]]) flag=1;
        }
        if (flag) cout<<"no"<<endl;
        else cout<<"yes"<<endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/hhlya/p/13262369.html