#include // #define int long long // #define uint unsigned long long #define il inline #define ct const #define dl double #define pk push_back #define fi first #define N 3010 #define se second #define pii pair // #define inf (int)(1000000000000000000) using namespace std; #define lowbit(x) (x&-x) #define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++) char buf[1<<21],*p1=buf,*p2=buf; il int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0'&&ch<='9'){ x=(x<<1)+(x<<3)+(ch^48);ch=getchar(); } return x*f; } char f__[40]; il void write(int x){ int cnt=0; if(x<0){ putchar('-');x=-x; } if(!x) putchar('0'); while(x){ f__[cnt++]=x%10+'0';x/=10; } while(cnt) putchar(f__[--cnt]); } int n,p[N],sum[N][N],f[N],g[N],s[N][N]; int stk[N],top,id[N]; signed main(){ // freopen("1.in","r",stdin); // freopen("1.out","w",stdout); n=read(); for(int i=1;i<=n;++i) p[i]=read(); for(int i=1;i<=n;++i){ for(int j=1;j<=i;++j) ++sum[i][p[j]]; for(int j=1;j<=n;++j) sum[i][j]+=sum[i][j-1]; } for(int i=0;i<=n;++i){ for(int j=i+1;j<=n;++j){ s[i][j]=s[i][j-1]+sum[i][n]-sum[i][p[j]]; } } memset(f,0x3f,sizeof(f)); memset(g,0x3f,sizeof(g)); f[0]=0; for(int j=1;j<=n;++j){ stk[top=1]=n;id[1]=0; for(int i=1;i<=n;++i){ while(top&&stk[top]=f[i]+s[i][stk[top]]){ --top;continue; } int l=i+1,r=stk[top]-1; while(l<=r){ // cerr<<"ERROR"; int mid=(l+r)>>1; if(f[id[top]]+s[id[top]][mid]<=f[i]+s[i][mid]) r=mid-1; else l=mid+1; } --l; if(l>i){ stk[++top]=l;id[top]=i; } break; } if(!top){ stk[top=1]=n;id[top]=i; } } write(g[n]);putchar('\n'); memcpy(f,g,sizeof(f)); } return 0; }