LightOJ

来源:互联网 发布:python snmp 系统监控 编辑:程序博客网 时间:2024/06/01 10:03

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 integers i 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 between i 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


题意:给你一个区间,要你求区间内的数,有多少个是回文数(12321这种)。


解题思路:数位DP,做完这题,对数位DP中的递归理解更深刻了。具体参考代码注释。




#include<iostream>#include<deque>#include<memory.h>#include<stdio.h>#include<map>#include<string.h>#include<algorithm>#include<vector>#include<math.h>#include<stack>#include<queue>#include<set>#include<bitset>using namespace std;typedef long long int ll;ll dp[90][90];//第i位,回文串长度为j的回文串个数int dig[32];int num[32];//记录前面一半的数字,用于判断回文int k;//当前位置,回文串长度,是否前导0ll dfs(int pos,int len,bool have,bool limit){    if(pos==-1)        return 1;//0肯定是回文串    //记忆化搜索    if(!limit && !have && dp[pos][len]!=-1){        return dp[pos][len];    }    int end=limit?dig[pos]:9;    ll ans=0;    for(int i=0;i<=end;i++){        if(have){            num[len]=i;            ans+=dfs(pos-1,len-!i,have&&i==0,limit&&i==end);//如果有前导0        }        else{            int mid=((len+1)/2);            //如果长度是偶数,中间点处理要特殊点……            if(len&1){                if(pos<mid){//这个时候要判断回文了                    if(num[2*mid-pos-1]==i)//是回文的话,继续看看下一位是不是回文                        ans+=dfs(pos-1,len,have&&i==0,limit&&i==end);                    //如果不是回文,函数就返回了。                }                else{                    num[pos]=i;//还在mid前,先记录数字                    ans+=dfs(pos-1,len,have&&i==0,limit&&i==end);                }            }            else{                                if(pos==mid){                    ans+=dfs(pos-1,len,have&&i==0,limit&&i==end);                }                else{                    if(pos<mid){                        if(num[mid*2-pos]==i)                            ans+=dfs(pos-1,len,have&&i==0,limit&&i==end);                    }                    else{                        num[pos]=i;                        ans+=dfs(pos-1,len,have&&i==0,limit&&i==end);                    }                }            }        }    }    if(!limit&&!have)        dp[pos][len]=ans;    return ans;}ll solve(ll x){    int pos=0;    while(x){        dig[pos++]=x%10;        x/=10;    }    return dfs(pos-1,pos-1,1,1);}int main(){    int t;    scanf("%d",&t);    ll l,r;    memset(dp,-1,sizeof(dp));    for(int qqq=1;qqq<=t;qqq++){        scanf("%lld%lld",&l,&r);        if(l>r)            swap(l,r);        printf("Case %d: %lld\n",qqq,solve(r)-solve(l-1));    }    return 0;}




原创粉丝点击