最长不下降子序列问题

来源:互联网 发布:ie11不支持js 编辑:程序博客网 时间:2024/06/06 02:09

DP

最大不下降子序列

前几天看了关于动态规划的内容,基本上讲的都是最大不下降序列,所以第一次博客
就写这个东西了。

最基本模板

给出一系列的数,给出一个整数,即最长不下降子序列(code vs 1567)

题解:

先另创一个数组,用来记录某一个数到目前为止的最大长度,用for语句将所有元素遍历
一遍就可以确定最长不下降子序列的长度了。
比如给出:21 22 63 15
从63开始(15不需要,其本身长度即为1),没有元素比他大,故它的长度还是1,然后
是22,后面有一个元素比它大,所以其长度为1+1(本身长度)=2,对于21寻找比它大的且长度
最大的元素,即22(长度为2),故该元素长度为3。此时遍历完毕,最大值为3。

下面上代码:

#include<iostream>#include<stdio.h>using namespace std;int a[5000],dp[5000];int main(void){    int n,len=1;    cin>>n;    for(int i=1;i<=n;i++)    {        cin>>a[i];        dp[i]=1;    }    for(int i=2;i<=n;i++)    //其实从前从后遍历都一样    {        for(int j=1;j<i;j++)        {            if(a[i]>a[j])            {                dp[i]=max(dp[j]+1,dp[i]);            }        }        len=max(len,dp[i]);    }    cout<<len<<endl;}  

另解
可以另开一个堆栈数组stack[],每次取栈顶的元素stack[top]和读到的元素temp
比较,如果temp>top,则将temp压入栈顶,如果temp

#include<iostream>#include<stdio.h>#include<cstdlib>using namespace std;int main(void){int i,j,n,top,temp;int stack[1001];cin>>n;top=0;stack[0]=-1;for(i=0;i<n;i++){  cin>>temp;  if(temp>stack[top])  {    stack[top++]=temp;  }  else  {    int low=1,high=top;    int mid;    while(low<high)    {      mid=(low+high)/2;      if(temp>stack[mid])      {        low=mid+1;      }      else      {        high=mid-1;      }     }    stack[mid]=temp;  }}cout<<top<<endl;     //话说我写代码都不喜欢写return的。。。}

关于这个最长不下降子序列有一道题:拦截导弹(NOIP1999)
题解:
这题第一问其实就是最长不上升子序列问题,之前有讲,然后第二问其实就是问有
几个最长不上升子序列,这个要用一个定理,书上写的是:即一个序列中不上升
子序列的最小覆盖数等于序列中最长上升序列的长度。(这什么鬼话,表示并没有
看懂)其实说白了就是该问可以转化为求最长不下降子序列的长度(至于为什么
,因为前面那个没有看懂的定理,反正用就好咯)
下面是代码:

#include<iostream>#include<stdio.h>#include<cstdlib>#include<string.h>using namespace std;int dp[5000],a[5000];int main(void){int i,j,n=1,len=0,count=0;while(scanf("%d",&a[n])!=EOF)  n++;for(i=1;i<n;i++){  dp[i]=1;  for(j=1;j<=i;j++)  {    if(a[i]<a[j]&&dp[i]<dp[j]+1)      dp[i]=dp[j]+1;    if(dp[i]>len)      len=dp[i];  }}memset(dp,0,sizeof(dp));for(i=1;i<=n;i++){  dp[i]=1;  for(j=1;j<=i;j++)  {    if(a[i]>a[j]&&dp[i]<dp[j]+1)      dp[i]=dp[j]+1;    if(count<dp[i])      count=dp[i];  }}cout<<len<<'\n'<<count<<endl;} 
0 0