lightoj - 1205 Palindromic Numbers (数位dp)好

1205 - Palindromic Numbers
Time Limit: 2 second(s)Memory Limit: 32 MB

A palindromic number or numeral palindrome is a'symmetrical' number like 16461 that remains the same when its digits arereversed. In this problem you will be given two integersi j, you haveto find the number of palindromic numbers between i and j (inclusive).

Input

Input starts with an integer T (≤ 200),denoting the number of test cases.

Each case starts with a line containing two integers i j(0 ≤ i, j ≤ 1017).

Output

For each case, print the case number and the total number ofpalindromic numbers betweeni and j (inclusive).

Sample Input

Output for Sample Input

4

1 10

100 1

1 1000

1 10000

Case 1: 9

Case 2: 18

Case 3: 108

Case 4: 198

 

思路:dp[st][cur][s]表示回文从st开始,到达当前位置,是否是回文数字答案是多少

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=20;
typedef long long LL;
LL L,R;
int dig[maxn];
LL dp[maxn][maxn][2];
int tmpdig[maxn];
LL dfs(int st,int cur,int s,int e)
{
    if(cur<0)return s;
    if(!e&&dp[st][cur][s]!=-1)
        return dp[st][cur][s];
    int end=(e?dig[cur]:9);
    LL ans=0;
    for(int i=0;i<=end;i++)
    {
        tmpdig[cur]=i;
        if(st==cur&&!i)
            ans+=dfs(st-1,cur-1,s,e&&i==end);
        else if(s&&cur<(st+1)/2)//后半段判断与前面的前半段是否构成回文
            ans+=dfs(st,cur-1,i==tmpdig[st-cur],e&&i==end);
        else//前半段填充
            ans+=dfs(st,cur-1,s,e&&i==end);
    }
    if(!e)dp[st][cur][s]=ans;
    return ans;
}
LL solve(LL n)
{
    if(n<0)return 0;
    else if(n==0)return 1;
    int len=0;
    while(n)
    {
        dig[len++]=n%10;
        n/=10;
    }
    dig[len]=0;
    return dfs(len-1,len-1,1,1);
}
int main()
{
    int T,cas=1;
    scanf("%d",&T);memset(dp,-1,sizeof(dp));
    while(T--)
    {
        scanf("%lld%lld",&L,&R);
        if(L>R)swap(L,R);
        printf("Case %d: %lld\n",cas++,solve(R)-solve(L-1));
    }
    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值