题目传送门
解题思路:
求一遍最长不下降和不上升子序列,然后总长度减去较大的长度.
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 5 using namespace std; 6 7 int n,a[30001],f[30001],dp[30001],len,tot; 8 9 int main() { 10 scanf("%d",&n); 11 for(int i = 1;i <= n; i++) 12 scanf("%d",&a[i]); 13 f[++len] = a[1]; 14 for(int i = 2;i <= n; i++) { 15 if(a[i] >= f[len]) { 16 f[++len] = a[i]; 17 continue; 18 } 19 int u = upper_bound(f+1,f+len+1,a[i]) - f; 20 f[u] = a[i]; 21 } 22 dp[++tot] = a[1]; 23 for(int i = 2;i <= n; i++) { 24 if(a[i] <= dp[tot]) { 25 dp[++tot] = a[i]; 26 continue; 27 } 28 int u = upper_bound(dp+1,dp+len+1,a[i],greater<int>()) - dp; 29 dp[u] = a[i]; 30 } 31 printf("%d",n - max(tot,len)); 32 return 0; 33 }