Roughly test instructions: Given the height of a team of soldiers, they were not sorted by height at first. The minimum number of people is required to dequeue, so that the original sequence of the soldier's height increases first and then decreases.
To increment and decrement is not difficult to think of incrementing the subsequence, requiring the least number of people to dequeue, that is, the original queue of the most people.
1 2 3 4 5 4 3 2 1
The first half of the sequence is incremented from left to right, and the first half is incremented from right to left. So let's first separate the LIS from left-right and right-to-left.
If the result is this:
a[i]={1.86 1.86 1.30621 2 1.4 1 1.97 2.2}//Original queue
A[i]={1 1 1 2 2 1 3 4}
B[i]={3 3 2 3 2 1 1 1}
If it is a[1]~a[i] increment, a[i+1]~a[8] decrements. This is the maximum value of a value between a value of a[1]~a[i] and b[i+1]~b[8].
Both O (n^2) and O (NLOGN) algorithms can be used.
O (n^2) algorithm:
#include <iostream>#include<cstdio>using namespacestd;Const intmax=1e3+5;intMain () {//freopen ("In.txt", "R", stdin); intN; scanf ("%d",&N); Doublea[max]={0}; for(intI=0; i<n; i++) scanf ("%f", A +i); intl[max]= {0},r[max]= {0}; l[0]=r[n-1]=1; for(inti =1; I < n; i++) { intMaxLen =0; for(intj =0; J < I; J + +) if(a[j]<A[i]) maxlen=Max (maxlen,l[j]); L[i]= MaxLen +1; } for(inti=n-2; i>=0; i--) { intmaxlen=0; for(intj=n-1; j>i; j--) if(a[j]<A[i]) maxlen=Max (maxlen,r[j]); R[i]=maxlen+1; } intmaxlen=0; for(intI=0; i<n-1; i++) for(intj=i+1; j<n;j++) MaxLen=max (maxlen,l[i]+R[j]); printf ("%d\n", N-maxlen); return 0;}
O (NLOGN) algorithm
#include <iostream>#include<cstdio>using namespacestd;Const intmax=1e3+5;intl[max]= {0},r[max]= {0};DoubleB[max];intBinarySearch (Double*a,DoubleValueintN) { intLow =0; intHigh = n-1; while(Low <=High ) { intMid = (high + low)/2; if(A[mid] = =value)returnmid; Else if(value<A[mid]) high= Mid-1; Else Low= Mid +1; } returnLow ;}intLis_dp_nlogn (Double*a,intNint*Len) { intNlislen =1; b[0] = a[0]; for(inti =1; I < n; i++) { if(A[i] > B[nlislen-1]) {B[nlislen]=A[i]; Nlislen++; Len[i]=Nlislen; } Else { intpos =BinarySearch (B, A[i], Nlislen); B[pos]=A[i]; Len[i]=pos+1; } } returnNlislen;}intMain () {//freopen ("In.txt", "R", stdin); intN; scanf ("%d",&N); Doublea[max]={0}; Doubleb[max]={0}; l[0]=r[0]=1; for(intI=0; i<n; i++) {scanf ("%f", A +i); B[n-i-1]=A[i]; } lis_dp_nlogn (a,n,l); Lis_dp_nlogn (B,N,R); intmaxlen=0; for(intI=0; i<n-1; i++) for(intj=n-i-2; j>=0; j--) MaxLen=max (maxlen,l[i]+R[j]); printf ("%d\n", N-maxlen); return 0;}
POJ 1836 Alignment The deformation of the longest increment subsequence (LIS)