您的位置:首页 > 其它

POJ 1836 Alignment (最长上升 下降子序列)

2016-11-03 11:08 176 查看
Description

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


       题目大意:对一排士兵重新排序,使新队列每个兵向左或向右都能看到左端或者右端,也就是使新队列的每个士兵的身高呈三角形分布即可。求出需要让最少个士兵退出才能完成。

       解法:此处借用小优博客的图说明这个问题,对士兵们进行遍历,使每个士兵作为下图的绿色柱子,下一个士兵作为红色柱子,然后每次循环求出绿色士兵之前最长上升子序列,以及红色士兵之后的最长下降子序列,士兵总人数减去这两个数之和,就得到了结果,然后在比较出最小的数就行了。



在这里,求最长上升子序列的方法如果用一般的方法,则复杂度为O(n^2),两次DP也就是O(2*n^2),加上最后找最大值的O(nlongn)可以忽略不计,普通的DP完全可以做出来。

 代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int dp1[1010],dp2[1010];
double a[1010];
int main()
{
int i,j,n;
while(~scanf("%d",&n))
{
memset(dp1,0,sizeof(dp1));
memset(dp2,0,sizeof(dp2));
for(i=0; i<n; i++)
scanf("%lf",&a[i]);
for(i=0; i<n; i++)//上升子序列
{
dp1[i]=1;
for(j=0; j<i; j++)
{
if(a[i]>a[j])
dp1[i]=max(dp1[i],dp1[j]+1);
}
}

for(i=n-1; i>=0; i--)//下降子序列
{
dp2[i]=1;
for(j=n-1; j>i; j--)
{
if(a[i]>a[j])
dp2[i]=max(dp2[i],dp2[j]+1);
}
}
int res=0;
for(i=0; i<n; i++)//找到最长的上升+下降序列
for(j=i+1; j<n; j++)
res=max(res,dp1[i]+dp2[j]);//记录最大值
printf("%d\n",n-res);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: