In the army, a platoon is composed by n soldiers. During the morning inspection, the soldiers are aligned in a straight line in front of the captain. The captain is not satisfied with the way his soldiers are aligned; it is true that the soldiers are aligned in order by their code number: 1 , 2 , 3 , . . . , n , but they are not aligned by their height. The captain asks some soldiers to get out of the line, as the soldiers that remain in the line, without changing their places, but getting closer, to form a new line, where each soldier can see by looking lengthwise the line at least one of the line's extremity (left or right). A soldier see an extremity if there isn't any soldiers with a higher or equal height than his height between him and that extremity.
Write a program that, knowing the height of each soldier, determines the minimum number of soldiers which have to get out of line.
Input
On the first line of the input is written the number of the soldiers n. On the second line is written a series of n floating numbers with at most 5 digits precision and separated by a space character. The k-th number from this line represents the height of the soldier who has the code k (1 <= k <= n).
There are some restrictions:
• 2 <= n <= 1000
• the height are floating numbers from the interval [0.5, 2.5]
Output
The only line of output will contain the number of the soldiers who have to get out of the line.
Sample Input
8 1.86 1.86 1.30621 2 1.4 1 1.97 2.2
Sample Output
4
题意:
有n个士兵排成一列,将军想从中抽出最少人数使队伍中任何士兵都能够看到左边最远处或右边最远处
思路;
要求最少出列数,就是留队士兵人数最大,即左边的递增序列人数和右边的递减序列人数之和最大
从前往后:对第i个人求1~i的以i结尾的最长上升子序列的长度
从后往前:对第i个人求n~i的以i结尾的最长上升子序列的长度
总长度就是这两个值相加减1,再用N-最多剩余的长度,即为最少去除的。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int dp1[1100],dp2[1100];//dp1[]从前往后;dp2[]从后往前
double s[1100];
int n;
int main()
{
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)
{
scanf("%lf",&s[i]);
dp1[i]=1;//初始化
dp2[i]=1;
}
int len=0;//剩余士兵的最大长度
for(int i=1;i<=n;i++)//求最长上升子序列dp1[]
{
for(int j=1;j<=i-1;j++)
{
if(s[j]<s[i])
dp1[i]=max(dp1[i],dp1[j]+1);
}
}
for(int i=n;i>=1;i--)//求最长下降子序列dp2[]
{
for(int j=i+1;j<=n;j++)
{
if(s[j]<s[i])
dp2[i]=max(dp2[i],dp2[j]+1);
}
}
for(int i=1;i<=n;i++)//判断最高点
{
int flag=1;//标记最高点
for(int j=i-1;j>=1;j--)
{
if(s[j]==s[i])//找到i前面的离i最近的与s[i]相等的点,更新dp1[i]
{
dp1[i]=max(dp1[i],dp1[j]+1);
flag=0;
break;
}
}
for(int j=i+1;j<=n;j++)
{
if(flag&&s[j]==s[i])
{
dp2[i]=max(dp2[i],dp2[j]+1);//先判断前面有没有算过最高点(s==0),若没算过,找到i后面的离i最近的与s[i]相等的最高点,更新dp2[i]
break;
}
}
len=max(len,dp1[i]+dp2[i]-1);//更新最大长度
}
printf("%d\n",n-len);//最小删除的长度
}
return 0;
}