用O(nlgn)復雜度的LIS算法
[cpp]
#include<cstdio>
const int maxsize=1000010;
int A[2][maxsize],B[2][maxsize],dp[2][maxsize];
void LIS(int flag,int n)
{
int left,right,mid,len=1;
B[flag][0]=A[flag][0];
int i;
for(i=1;i<n;++i)
{
left=0;right=len-1;
while(left<=right)
{
mid=(left+right)/2;
if(B[flag][mid]>A[flag][i])
right=mid-1;
else
if(B[flag][mid]==A[flag][i])
{
left=mid;
break;
}
else
left=mid+1;
}
B[flag][left]=A[flag][i];
if(left==len)
++len;
dp[flag][i]=left+1;
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i;
for(i=0;i<n;i++)
{
scanf("%d",&A[0][i]);
A[1][n-i-1]=A[0][i];
}
LIS(0,n);
LIS(1,n);
int max=0;
dp[0][0]=dp[1][0]=1;
for(i=0;i<n;i++)
{
if(dp[0][i]+dp[1][n-i-1]>max)
max=dp[0][i]+dp[1][n-i-1];
}
printf("%d\n",n-max+1);
}
return 0;
}
#include<cstdio>
const int maxsize=1000010;
int A[2][maxsize],B[2][maxsize],dp[2][maxsize];
void LIS(int flag,int n)
{
int left,right,mid,len=1;
B[flag][0]=A[flag][0];
int i;
for(i=1;i<n;++i)
{
left=0;right=len-1;
while(left<=right)
{
mid=(left+right)/2;
if(B[flag][mid]>A[flag][i])
right=mid-1;
else
if(B[flag][mid]==A[flag][i])
{
left=mid;
break;
}
else
left=mid+1;
}
B[flag][left]=A[flag][i];
if(left==len)
++len;
dp[flag][i]=left+1;
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i;
for(i=0;i<n;i++)
{
scanf("%d",&A[0][i]);
A[1][n-i-1]=A[0][i];
}
LIS(0,n);
LIS(1,n);
int max=0;
dp[0][0]=dp[1][0]=1;
for(i=0;i<n;i++)
{
if(dp[0][i]+dp[1][n-i-1]>max)
max=dp[0][i]+dp[1][n-i-1];
}
printf("%d\n",n-max+1);
}
return 0;
}