Palindromic Numbers (数位dp)

来源:互联网 发布:个人数据融合算法 编辑:程序博客网 时间:2024/05/20 21:48

A palindromic number or numeral palindrome is a 'symmetrical' number like 16461 that remains the same when its digits are reversed. In this problem you will be given two integersi j, you have to 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 of palindromic numbers betweeni and j (inclusive).

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

题目大概:

输出n和m之间的回文数(即23532这样的数字),n可能大于m。

思路:

先把前一半的数字存在一个数组里,然后到了后半部分,逆序对应比较即可,只要有一个不同便不是了。


代码:


#include <iostream>#include <cstring>#include <cstdio>using namespace std;typedef long long ll;int dig[20],now_dig[20];ll dp[20][20][2];ll sove(int len,int sta,int flag,int first) {    if(len==0)return (ll)flag;    if(dp[len][sta][flag]!=-1&&!first) return dp[len][sta][flag];    int t=(first?dig[len]:9);    ll res=0;    for(int i=0;i<=t;i++) {        now_dig[len]=i;        if(!i&&len==sta)        {            res+=sove(len-1,sta-1,flag,first&&i==t);        }        else if(flag&&len<=(sta+1)/2)        {            res+=sove(len-1,sta,i==now_dig[sta-len+1],first&&i== t);        }        else        {            res+=sove(len-1,sta,flag,first&&i==t);        }    }    if(!first)dp[len][sta][flag]=res;    return res;}ll go(ll x) {    if(x<0) return 0;    if(x==0) return 1;    int len=0;    while(x) {        dig[++len] = x%10;        x/=10;    }    return sove(len,len,1,1);}int main() {    int t;    ll n,m;    int Case=0;    scanf("%d",&t);    memset(dp,-1 ,sizeof(dp));    while(t--) {        scanf("%lld%lld",&m,&n);        if(m<n) swap(m,n);        printf("Case %d: %lld\n",++Case,go(m)-go(n-1));    }    return 0;}





原创粉丝点击