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 | 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问题,不一样的地方就是开个数组记录一下前一半已经选了的数字。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define endl '\n'
#define LL long long
using namespace std;
int a[20],t[20];
LL dp[20][20][2];
LL dfs(int len,int cur,int s,int fp)
{
if(!cur)
return s;
if(!fp && dp[len][cur][s] != -1)
return dp[len][cur][s];
int n = fp?a[cur]:9;
LL res = 0;
for(int i=0;i<=n;i++)
{
t[cur] = i;
if(len == cur && i == 0)
res += dfs(len-1,cur-1,s,fp&&i==n);
else if(s && cur <= (len+1)/2)
res += dfs(len,cur-1,t[len-cur+1]==i,fp&&i==n);
else
res += dfs(len,cur-1,s,fp&&i==n);
}
if(!fp)
dp[len][cur][s] = res;
return res;
}
LL sum(LL x)
{
int len = 0;
while(x)
{
a[++len] = x % 10;
x /= 10;
}
return dfs(len,len,1,1);
}
int main(void)
{
int T;
scanf("%d",&T);
memset(dp,-1,sizeof(dp));
int cas = 1;
while(T--)
{
LL a,b;
scanf("%lld%lld",&a,&b);
if(a > b)
swap(a,b);
printf("Case %d: %lld\n",cas++,sum(b) - sum(a-1));
}
return 0;
}