題目要求的是最長下降子序列的長度。長度爲n的串的最長子序列長度必定存在最優子結構。
證明:
若序列{x1,x2x3...xn}的最長下降子序列爲{y1,y2,y3,y4...yk},不妨假設yk=xm。則{y1,y2,y3...yk}也一定是序列{x1,x2,x3...xm}的最長子序列。否則,一定存在p>k,使得序列{x1,x,x3...xn}的最優解爲p>k。與假設矛盾。
因此,可以採用dp 的做法。
dp數組初始化爲1.
dp[i]表示以第i位爲結尾的最長下降子序列的長度。
dp[i]=max(dp[j]+1),(0<=j<i<n&&num[j]>=num[i])
最後選出最大的dp值爲ans。
算法複雜度爲O(n^2)
#include <cstdio>
using namespace std;
int afx[32768];
int dp[32768];
int main()
{
for(int c=1;;c++)
{
scanf("%d",afx);
if(afx[0]==-1)
break;
int i;
for(i=1;;i++)
{
scanf("%d",afx+i);
if(afx[i]==-1)
break;
}
for(int a=0;a<i;a++)
dp[a]=1;
int ans=1;
for(int b=1;b<i;b++)
{
int max=1;
for(int j=0;j<b;j++)
if(afx[j]>=afx[b]&&dp[j]+1>max)
max=dp[j]+1;
dp[b]=max;
if(max>ans)
ans=max;
}
printf("Test #%d:\n maximum possible interceptions: %d\n\n",c,ans);
}
return 0;
}