给一个长为 n 的序列 a ,请问要在这个序列中删除长度为多少的前缀,才能使这个序列是一个完美序列。
完美序列的定义:完美序列的定义为:假定有一个序列 b,你可以每次从序列的首项或末项取出一个数字放在序列 c 的末尾。假如存在一种方案使得 c 为不降序列,那么 b 就是完美序列。
第一行一个整数 n$$(n\le2000),表示序列 a 的长度。
第二行 n 个数,a1,a2,a3,......,an,对于序列 a 中的每一个元素,都有 0≤ai≤106
求把序列 a 变成一个完美序列最少需要删除长度为多少的前缀。
错误原因:
老师给我的递归代码来了一组 hack:
7
4 3 3 8 4 5 2
正确的输出:4
我的:
4
5
6
7
所以球球 DL 们告诉我错在哪里了,好吗?
代码:
#include<bits/stdc++.h>
using namespace std;
int read() {
register int x = 0,f = 1;register char ch;
ch = getchar();
while(ch > '9' || ch < '0'){if(ch == '-') f = -f;ch = getchar();}
while(ch <= '9' && ch >= '0'){x = x * 10 + ch - 48;ch = getchar();}
return x * f;
}
int a[2000],n,m=0;
void search(int x,int y,int z){// x 和 y 表示搜索的范围,z 表示元素必须大于等于 z,w 表示现存的元素数。
if(x>=y){
if(a[x]>=z){
printf("%d\n",m);
return;
}
else{
++m;search(m,n-1,0);
}
}
if(a[x]<z && a[y]<z){
++m;search(m,n-1,0);
}
else if(a[x]<z)search(x,y-1,a[y]);
else if(a[y]<z)search(x+1,y,a[x]);
else{
if(a[x]>=a[y])search(x,y-1,a[y]);
else search(x+1,y,a[x]);
}
}
int main(){
#ifdef ONLINE_JUDGE
freopen("perfect.in","r",stdin);
freopen("perfect.out","w",stdout);
#endif
t=read();n=read();
for(int i=0;i<n;i++){
a[i]=read();
}
search(0,n-1,0);
return 0;
}