1205 - Palindromic Numbers
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 arereversed. In this problem you will be given two integersi j, you haveto 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 ofpalindromic numbers betweeni 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 |
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=20;
typedef long long LL;
LL L,R;
int dig[maxn];
LL dp[maxn][maxn][2];
int tmpdig[maxn];
LL dfs(int st,int cur,int s,int e)
{
if(cur<0)return s;
if(!e&&dp[st][cur][s]!=-1)
return dp[st][cur][s];
int end=(e?dig[cur]:9);
LL ans=0;
for(int i=0;i<=end;i++)
{
tmpdig[cur]=i;
if(st==cur&&!i)
ans+=dfs(st-1,cur-1,s,e&&i==end);
else if(s&&cur<(st+1)/2)//后半段判断与前面的前半段是否构成回文
ans+=dfs(st,cur-1,i==tmpdig[st-cur],e&&i==end);
else//前半段填充
ans+=dfs(st,cur-1,s,e&&i==end);
}
if(!e)dp[st][cur][s]=ans;
return ans;
}
LL solve(LL n)
{
if(n<0)return 0;
else if(n==0)return 1;
int len=0;
while(n)
{
dig[len++]=n%10;
n/=10;
}
dig[len]=0;
return dfs(len-1,len-1,1,1);
}
int main()
{
int T,cas=1;
scanf("%d",&T);memset(dp,-1,sizeof(dp));
while(T--)
{
scanf("%lld%lld",&L,&R);
if(L>R)swap(L,R);
printf("Case %d: %lld\n",cas++,solve(R)-solve(L-1));
}
return 0;
}