码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划-最长不下降子序列

时间:2018-02-08 00:35:01      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:tor   one   math.h   names   pos   size   top   子序列   tac   

代码:

技术分享图片
#include <stdio.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>


#define I scanf
#define OL puts
#define O printf
#define F(a,b,c) for(a=b;a<c;a++)
#define FF(a,b) for(a=0;a<b;a++)
#define FG(a,b) for(a=b-1;a>=0;a--)
#define LEN 101
#define MAX 1<<30
#define V vector<int>

using namespace std;

int a[LEN];
int dp[LEN];
int n;

void printAns(int cnt,int pos,V vec){
    vec.insert(vec.begin(),a[pos]);
    int obj=dp[pos--]-1;
    while(pos>0){
        if(dp[pos]==obj)
            printAns(cnt-1,pos,vec);
        pos--;
    }
    if(cnt==1){
        int i;
        FF(i,vec.size())
            O("%d ",vec[i]);
        OL("");
    }
}

void DP_n2(){
    int i,j,p;
    int ans=0;
    F(i,1,n+1){
        dp[i]=1;
        F(j,1,i){
            if(a[j]<a[i])
                dp[i]=max(dp[i],dp[j]+1);
        } 
        if(dp[i]>ans){
            ans=dp[i];
            p=i;
        }
    }
    O("ans=%d p=%d\n序列 :\n",ans,p);
    F(i,1,n+1)O("%d ",a[i]) ;
    OL("\nDP数组 :");
    F(i,1,n+1)O("%d ",dp[i]) ;
    OL("");
    V vec;
    OL("所有LIS :");
    printAns(ans,p,vec);
} 

void DP_nLogn(){
    int i,j,top=0;
    F(i,1,n+1){
        if(top==0 || dp[top-1]<a[i]) 
            dp[top++]=a[i];
        else{
            int pos=lower_bound(dp,dp+top,a[i])-dp;
            dp[pos]=a[i];
        }
    }
    printf("%d\n",top);
    OL("DP数组: ");
    F(i,0,top)O("%d ",dp[i]);
    OL("\n") ;
}
int main()
{   
//dilworth定理:LIS 长度   等于  LIS 子序列 个数
    freopen("LIS.txt","r",stdin);
    int i,j;
    I("%d",&n);
    F(i,1,n+1){
        I("%d",&a[i]);
    }
    
    DP_nLogn();
    DP_n2();
    return 0;
}
View Code

测试数据:

11
1 3 7 6 8 5 3 2 7 2 9

 

动态规划-最长不下降子序列

标签:tor   one   math.h   names   pos   size   top   子序列   tac   

原文地址:https://www.cnblogs.com/TQCAI/p/8428598.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!