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 分析:令到原队列的最少士兵出列后,使得新队列任意一个士兵都能看到左边或者右边的无穷远处,即使新队列呈三角形分布。具体步骤为:1.求最长不降子序列 2.求最长不升子序列 3.得到最大的子序列和k,所求的最少出列人数=n-k需要特别注意的是:最中间两个士兵身高可以相同。例如:5 5 5 这种情况,输出结果应为 1。 代码实现:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<string> 5 #include<algorithm> 6 using namespace std; 7 const int MAX=1005; 8 double a[MAX]; 9 int up[MAX],down[MAX]; 10 11 int main() 12 { 13 int n,i,j,k; 14 scanf("%d",&n); 15 for(i=1;i<=n;i++) 16 scanf("%lf",&a[i]); 17 18 memset(up,0,sizeof(up)); 19 memset(down,0,sizeof(down)); 20 21 up[1]=1; 22 for(i=2;i<=n;i++) 23 { 24 up[i]=1; 25 for(j=i-1;j>=1;j--) 26 { 27 if(a[i]>a[j] &&up[i]<up[j]+1) 28 up[i]=up[j]+1; 29 } 30 } 31 32 down[n]=1; //注意将down[n]初始化为1 33 for(i=n-1;i>=1;i--) 34 { 35 down[i]=1; 36 for(j=i+1;j<=n;j++) 37 { 38 if(a[i]>a[j] && down[i]<down[j]+1) 39 down[i]=down[j]+1; 40 } 41 } 42 43 k=up[n]; //k=up[n]而不是up[1]; 44 for(i=1;i<n;i++) 45 { 46 for(j=i+1;j<=n;j++) 47 { 48 if(k<up[i]+down[j]) 49 k=up[i]+down[j]; 50 } 51 } 52 //cout<<k<<endl; 53 cout<<n-k<<endl; 54 return 0; 55 56 }