LOJ 1205 - Palindromic Numbers

又用数位DP写了一遍。。。

1205 - Palindromic Numbers
PDF (English) Statistics Forum
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 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 (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

 

#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
using namespace std;
#define ll long long
#define ERR puts("=======here========");
#define prt(k) cout<<#k"="<<k<<" "
#include<algorithm>

ll dp[88][88];
ll bit[99];
ll dfs(int len,int l,int r,bool limit,bool ok)
{
    if(l<r) return !limit||(limit&&ok);
    if(!limit&&~dp[len][l]) return dp[len][l];
    ll ret=0;
    ll end=limit?bit[l]:9;
    for(int i=0;i<=end;i++)
    {
        if(i==0&&l==len-1) continue;
        bool news;
        if(ok) news=i<=bit[r];else news=i<bit[r];
        ret+=dfs(len,l-1,r+1,limit&&i==end,news);
    }
    if(!limit) dp[len][l]=ret;
    return ret;
}
ll get(ll n)
{
    int len=0;  if(n<0) return 0;
    while(n)
    {
        bit[len++]=n%10;
        n/=10;
    }
    ll ret=1;
    for(int i=len;i>=1;i--) ret+=dfs(i,i-1,0,i==len,1);
    return ret;
}
int main()
{
    ll l,r; int re; cin>>re;  int ca=1;
    memset(dp,-1,sizeof dp);
    while(re--)
    {
        cin>>l>>r; if(l>r) swap(l,r);
        printf("Case %d: %lld\n",ca++,get(r)-get(l-1));
        //cout<<get(r)-get(l-1)<<endl;
    }
}


你可能感兴趣的:(数据结构,算法,搜索,ACM)