hdu4352 XHXJ's LIS

来源:互联网 发布:软件外包服务专业 编辑:程序博客网 时间:2024/06/06 03:04

http://acm.hdu.edu.cn/showproblem.php?pid=4352

把数看成一个数字串,然后求区间[L,R]内最长上升子序列(LIS,不连续)长度为K的数字的个数。

数位DP,想了半下午想不出,主要卡在状态的压缩上。。因为LIS要求记录长度为i的子序列中,其最小的结尾数字。K小于等于10,就要记录10个数,每个数的取值范围是0到9,这样状态就压到十亿了QAQ。。然后就一直在考虑怎么继续压缩状态,思维一直僵化在这里。后来看了题解才知道可以不去理会长度,因为是严格递增,LIS中出现过的数不会重复出现,范围又是从0到9共10个数字。所以2^10就可以存下,记忆化搜索的状态明确了,其他的就很简单了。。

代码:

#include<cstdio>#include<cstring>using namespace std;typedef __int64 ll;ll dp[20][1<<10][12];int bit[20],K;ll dfs(int pos,int state,bool zero,bool flag){    if(pos==-1){        if(zero) return 0;        int sum=0;        for(int i=0;i<10;++i) sum+=((state>>i)&1);        return sum==K;    }    if(!flag&&dp[pos][state][K]!=-1) return dp[pos][state][K];    ll ans=0;int res,to=flag?bit[pos]:9;    for(int i=0;i<=to;++i){        res=state;        if(!(zero&&i==0)){            if(((res>>i)&1)==0) res+=(1<<i);            if(res!=state){int j;                for(j=i+1;j<10&&(((res>>j)&1)==0);++j);                if(j<10) res-=(1<<j);            }        }        ans+=dfs(pos-1,res,zero&&(i==0),flag&&(i==to));    }    if(!flag) dp[pos][state][K]=ans;    return ans;}ll calc(ll n){    int pos=0;    while(n){        bit[pos++]=(n%10);        n/=10;    }    return dfs(pos-1,0,true,true);}int main(){    int t,Case=1;ll L,R;scanf("%d",&t);    memset(dp,-1,sizeof(dp));    while(t--){        scanf("%I64d%I64d%d",&L,&R,&K);        printf("Case #%d: %I64d\n",Case++,calc(R)-calc(L-1));    }    return 0;}

数位DP小trick比较多,需要考虑的是:如果考虑的这一位之前没有放置过数字(即全为0),怎么去处理。。这是注意点之一,以后再遇到会继续补充

0 0
原创粉丝点击