Codeforces1375 C. Element Extermination(單調棧)

You are given an array 𝑎 of length 𝑛, which initially is a permutation of numbers from 1 to 𝑛. In one operation, you can choose an index 𝑖 (1≤𝑖<𝑛) such that 𝑎𝑖<𝑎𝑖+1, and remove either 𝑎𝑖 or 𝑎𝑖+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 𝑖=1 (since 𝑎1=1<𝑎2=3), then either remove 𝑎1 which gives the new array [3,2], or remove 𝑎2 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 𝑡 (1≤𝑡≤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 𝑛 (2≤𝑛≤3⋅105) — the length of the array.

The second line of each test case contains 𝑛 integers 𝑎1, 𝑎2, …, 𝑎𝑛 (1≤𝑎𝑖≤𝑛, 𝑎𝑖 are pairwise distinct) — elements of the array.

It is guaranteed that the sum of 𝑛 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
Note
For the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation):

[1,2,3]→[1,2]→[1]
[3,1,2,4]→[3,1,4]→[3,4]→[4]
[2,4,6,1,3,5]→[4,6,1,3,5]→[4,1,3,5]→[4,1,5]→[4,5]→[4]

題意:
一個全排列。假設a[i]<a[i+1]a[i]<a[i+1],那麼你可以刪掉a[i]a[i]或者a[i+1]a[i+1]

思路:
a[1]<a[n]a[1]<a[n]則可以,否則不可以。

可以用單調棧理解,最優的策略是用某個區域內的最大值向前一直走,直到走到第一個數,就去掉這個最大值。或者用最小值往後走,直到走到最後一個數,去掉這個最小值。

這實際上是維護一個單調遞減棧。如果最後這個單調棧的大小不爲1,則不可以。
這個結果等價於a[1]<a[n]a[1]<a[n]

#include <cstdio>
#include <cstring>
 
 
using namespace std;
 
typedef long long ll;
 
const int maxn = 3e5 + 10;
int a[maxn];
 
int main() {
    int T;scanf("%d",&T);
    while(T--) {
        int n;scanf("%d",&n);
        for(int i = 1;i <= n;i++)
        {
            scanf("%d",&a[i]);
        }
        if(a[1] > a[n])
        {
            printf("NO\n");
        }
        else
        {
            printf("YES\n");
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章