Palindromic Numbers LightOJ - 1205 数位dp

Description
求[a,b]中回文数的个数
Input
第一行为用例组数t,之后t行每行两个整数a和b表示查询区间端点
Output
对于每组用例,输出区间[a,b]中回文数的个数
Sample Input
4
1 10
100 1
1 1000
1 10000
Sample Output
Case 1: 9
Case 2: 18
Case 3: 108
Case 4: 198

要有tmp数组记录前面的选的数字。然后记录一个起始未知的状态


LL dp[30][30][2];
int num[50];
int tmp[50];
LL dfs(int sta,int cur,int limit,int state){
    if(cur<0){return state;}
    if(!limit&&dp[sta][cur][state]!=-1)return dp[sta][cur][state];
    LL ret=0;
    int up=limit?num[cur]:9;
    for(int i=0;i<=up;++i){
        tmp[cur]=i;
        if(cur==sta&&i==0){ ret+=dfs(sta-1,cur-1,limit&&i==up,state); }
        else  if(state&&cur<(sta+1)/2){
            ret+=dfs(sta,cur-1,limit&&i==up,state&&i==tmp[sta-cur]);
        }
        else{ ret+=dfs(sta,cur-1,limit&&i==up,state); }
    }
    if(!limit)dp[sta][cur][state]=ret;
    return ret;
}
LL solve(LL n){
    LL tmp=n;
    int pos=0;
    while(tmp){
        num[pos++]=tmp%10;
        tmp/=10;
    }
    //pf("%d\n",pos);
    return dfs(pos-1,pos-1,1,1);
}
int main(){
    freopen("in.txt","r",stdin);
    int T;sf("%d",&T);
    mem(dp,-1);
    while(T--){
        LL l,r;
        sf("%lld%lld",&l,&r);
        if(l>r)swap(r,l);
        pf("%lld\n",solve(l-1));
        pf("%lld\n",solve(r));
        pf("%lld\n",solve(r)-solve(l-1));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值