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 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 <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
using namespace std;
int T;
typedef long long ll;
int bits[20];
ll dp[20][20];
ll dfs(int len,int l,int r,bool flag,bool ok)
{
if(r > l) return !flag || (flag && ok);
if(!flag && ~dp[len][l]) return dp[len][l];
int end = flag ? bits[l] : 9;
ll res = 0;
for(int i=0;i<=end;i++)
{
if(l == len && i == 0) continue;
bool g = ok;
if(ok) g = bits[r] >= i;
else g = bits[r] > i;
res += dfs(len,l-1,r+1,flag&&(i==end),g);
}
return flag ? res : dp[len][l] = res;
}
ll solve(ll x)
{
if(x < 0) return 0;
if(x == 0) return 1;
ll tt = x;
int cnt = 0;
while(tt >0 )
{
bits[++cnt] = tt % 10;
tt /= 10;
}
ll ret = 1;
for(int i=cnt;i>=1;i--)
ret += dfs(i,i,1,i==cnt,true);
return ret;
}
int main()
{
int C = 1;
scanf("%d",&T);
memset(dp,-1,sizeof(dp));
while(T --)
{
ll l,r;
scanf("%I64d%I64d",&l,&r);
if(l > r) swap(l,r);
printf("Case %d: %I64d\n",C++,solve(r)-solve(l-1));
}
return 0;
}