Codeforces 1375C题解

Codeforces 1375C题解

题目描述
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
input
4
3
1 2 3
4
3 1 2 4
3
2 3 1
6
2 4 6 1 3 5
output
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[1]<a[n],答案一定为“YES”,以下来证明:
当a[1]<a[n]时,我们反复使用以下算法(constructive algorithm)来处理含有>1元素的序列:
1.找到最小的下标r使得a[1]<a[r]
2.选择a[r]和a[r]的前一个元素比较,选择删除前一个元素的决策
3.重复步骤2的动作,直到a[r]的前一个元素就是a[1]
3.此时删除a[r]

(算法核心就是想办法让最后一组操作是在a[1]和a[n]两个元素间比较做出选择)

因为a[r]是第一个大于a[1]的元素,所以在i in [1…r]中,a[i]<a[1]<a[r],所以这中间的元素总是可以被删除。

如果a[1]>a[n]的话,我们可以观察到
1。最左边的元素是不递减的,因为如果我们想删掉原先最左边的元素a[1],就需要去匹配使得a[2]>a[1],这就会使得最左边的元素增长
2.同样地,也可以证明最右边的元素是不递增的

因此,最左边和最右边的元素这辈子都不可能匹配以删除一个元素

#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[300001];
	int t,n;
	cin>>t;
	while (t--){
	      cin>>n;
	      for (int i=0; i<n; i++)
			  cin>>a[i];
		  
		  if (a[0]<a[n-1])
		     cout<<"YES"<<endl;
		  else
		     cout<<"NO"<<endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值