LightOJ 1205 Palindromic Numbers(数位DP)

来源:互联网 发布:淘宝查号怎么查 截图 编辑:程序博客网 时间:2024/06/03 12:29

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
Solution
数位DP,用dp[start][cur][state]表示以start位起始到cur位状态为state(1表示已经回文,0表示没有回文)时回文数的个数,注意前置0的情况
Code

#include<cstdio>#include<cstring>#include<iostream>using namespace std;typedef long long ll;ll dp[20][20][2];int num[20],temp[20];ll dfs(int start,int cur,bool state,bool fp)//start表示回文串的起点,cur表示正在搜索的位,state表示目前构成的串是否为回文串 {    if(cur<0)        return state;    if(!fp&&dp[start][cur][state]!=-1)        return dp[start][cur][state];    int fpmax=fp?num[cur]:9;    ll ret=0;    for(int i=0;i<=fpmax;i++)    {        temp[cur]=i;//枚举该位的值         if(start==cur&&i==0)//前置0的情况             ret+=dfs(start-1,cur-1,state,fp&&i==fpmax);        else if(state&&cur<(start+1)/2)//已经构成回文串             ret+=dfs(start,cur-1,temp[start-cur]==i,fp&&i==fpmax);        else//尚未构成回文串             ret+=dfs(start,cur-1,state,fp&&i==fpmax);    }    if(!fp)         dp[start][cur][state]=ret;    return ret;}ll f(ll n){    int len=0;    while(n)    {        num[len++]=n%10;        n/=10;    }    num[len]=0;    return dfs(len-1,len-1,1,1);}int main(){    int T;    scanf("%d",&T);    int res=1;    memset(dp,-1,sizeof(dp));    while(T--)    {        ll a,b;        scanf("%lld%lld",&a,&b);        if(a>b)            swap(a,b);        printf("Case %d: %lld\n",res++,f(b)-f(a-1));    }    return 0;}
0 0
原创粉丝点击