#include <bits/stdc++.h> using namespace std; #define ll long long const int M = 1e5 + 1; int a[M]; int f[3][M]; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { if(a[j]<a[i]) f[0][i] = max(f[0][i], f[0][j] + 1); } } for (int i = n; i >= 1; i--) { for (int j = n + 1; j > i; j--) { if(a[j]<a[i]) f[1][i] = max(f[1][i], f[1][j] + 1); } } int mx = 0; for (int i = 1; i <= n; i++) { mx = max(f[0][i] + f[1][i] -1,mx); } cout << n-mx << endl; }
二分写法
#include <bits/stdc++.h> using namespace std; #define ll long long const int M = 1e5 + 1; int a[M]; int f1[M]; int f2[M]; int l[M]; int r[M]; int n; inline void solve1() { int len=1; l[1]=1; f1[1]=a[1]; for(int i=2;i<=n;i++){ if(a[i]>f1[len]) f1[++len]=a[i]; else{ int p=lower_bound(f1+1,f1+len+1,a[i])-f1; f1[p]=a[i]; } l[i]=len; } } inline void solve2() { int len=1; r[1]=1; f2[1]=a[n]; for(int i=n-1;i>=1;i--){ if(a[i]>f2[len]) f2[++len]=a[i]; else{ int p=lower_bound(f2+1,f2+len+1,a[i])-f2; f2[p]=a[i]; } r[i]=len; } } int main() { cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } solve1(); solve2(); int mx=1e3; for(int i=1;i<=n;i++){ mx=min(mx,n-l[i]-r[i+1]); } cout<<mx<<endl; }