Code Forces 1367A Sorting Parts 题解
(原题链接:CF传送门)
题目背景(我看不懂英文嘤嘤嘤)
Sorting Parts
You have an array a of length n. You can exactly once select an integer len between 1 and n−1 inclusively.
And then sort in non-decreasing order the prefix of the array of length len and the suffix of the array of length n−len independently.
For example, if the array is a=[3,1,4,5,2], and you choose len=2, then after that the array will be equal to [1,3,2,4,5].
Could it be that after performing this operation, the array will not be sorted in non-decreasing order?
翻译:给定一个数组a,其长度为n,现在从1到n-1中选任意一个len,对len前和len后的部分分别排序。若对于每一个len,均保证排序后的数组是有序的,输出“NO”,否则输出“YES”。
输入:测试组数t,数组长度n,a[i]的值。
输出:对于每组测试,输出“YES”或“NO”。
题意解析
这道题作为我打CF比赛的第一道题,也是2022-2-12CF全球赛的A题,其思路还是简单的。
首先想到的是暴力做法。
但是一看数据范围:1 ≤ t ≤ 100,2 ≤ n ≤ 104 ,1 ≤ a ≤109.
显然,用暴力妥妥的TLE。
那怎么办呢?
其实不用排序(这题目跟排序没关系好吗!)
仔细观察题目就可以发现:要使得最终的数组无序,只要满足“存在一个合法的 len 使得 len 前的最大值 大于 len 后的最小值”这一条件即可。
核心代码
用数组maxn[MAXN] , minn[MAXN]分别表示 从 a[1] 到 a[i] 的最大值,以及从 a[i] 到 a[n] 的最小值。
①初始化 maxn[] , minn[].
cin>>n;
for(int i=1; i<=n; i++) {
cin>>a[i];
maxn[i]=max(maxn[i-1],a[i]);
}//初始化 maxn[]
for(int i=n; i>=1; i--) {
if(i==n) {
minn[i]=a[i];
}//注意这一步!
if(i<n) {
minn[i]=min(minn[i+1],a[i]);
}
}//初始化 minn[]
②判断是否有序.
int flag=0;//用flag标注
for(int i=1; i<=n-1; i++) {
if(maxn[i]>minn[i]) {
flag=1;
break;
}
}
if(flag==1) {
cout<<"YES"<<endl;
} else {
cout<<"NO"<<endl;
}
代码展示
#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e4+5;
int a[MAXN];
int maxn[MAXN];
int minn[MAXN];
int t,n;
int flag=0;
int main() {
cin>>t;
while(t--) {
flag=0;
cin>>n;
for(int i=1; i<=n; i++) { //1
cin>>a[i];
maxn[i]=max(maxn[i-1],a[i]);
}//1
for(int i=n; i>=1; i--) { //2
if(i==n) {
minn[i]=a[i];
}
if(i<n) {
minn[i]=min(minn[i+1],a[i]);
}
}//2
for(int i=1; i<=n-1; i++) { //3
if(maxn[i]>minn[i]) {
flag=1;
break;
}
}//3
if(flag==1) {
cout<<"YES"<<endl;
} else {
cout<<"NO"<<endl;
}
}
return 0;
}
写在最后
求赞QAQ

-------------------------------------------
个性签名:そんなに形に拘らないの、大切なのは心よ
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!

浙公网安备 33010602011771号