Palindromic Numbers LightOJ - 1205

本文介绍了一种使用数位DP方法解决区间内回文数计数问题的算法实现。通过枚举数字的前半部分来填充后半部分,实现了高效地计算指定区间内的回文数个数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:

求区间内的回文数个数

 

题目思路:

  数位dp,先枚举前一半数字,然后填上相应的后一半数字。

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#define MAXSIZE 1000005
#define LL long long

using namespace std;

LL dp[55][55][2];
int temp[MAXSIZE],bit[MAXSIZE];

LL dfs(int pos,int st,int pre,int limit)
{
    if(pos < 1)
        return 1;
    if(!limit && dp[pos][st][pre]!=-1)
        return dp[pos][st][pre];
    int len = limit?bit[pos]:9;
    LL ans = 0;
    for(int i=0;i<=len;i++)
    {
        temp[pos] = i;
        if(pre==0 && i==0)
        {
            ans += dfs(pos-1,st-1,0,i==len&&limit);
        }

        else if(pos > st/2) //枚举前一半
        {
            ans += dfs(pos-1,st,1,i==len&&limit);
        }

        else if(temp[pos] == temp[st-pos+1]) //填上后一半
        {
            ans += dfs(pos-1,st,1,i==len&&limit);
        }
    }

    if(!limit)
        dp[pos][st][pre] = ans;
    return ans;
}

LL Solve(LL n)
{
    int pos = 0;
    memset(dp,-1,sizeof(dp));
    while(n)
    {
        bit[++pos] = n%10;
        n /= 10;
    }
    LL ans = dfs(pos,pos,0,1);
    return ans;
}

int main()
{
    int T,cns=1;
    LL n,m;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld",&n,&m);
        if(n > m)
            swap(n,m);
        LL ans = Solve(m) - Solve(n-1);
        printf("Case %d: %lld\n",cns++,ans);
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/alan-W/p/7676976.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值