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,开一个数组保存确实巧妙
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int a[30],b[30];
ll dp[30][30][30];
ll dfs(int pos,int s,bool sta,int lead,int limit)
//s表示回文串的起点,pos表示正在搜索的位,sta表示目前构成的串是否为回文串
{
if(pos==-1){
return sta;
}
if(!limit&&!lead&&dp[pos][s][sta]!=-1)
return dp[pos][s][sta];
int up=limit?a[pos]:9;
ll tmp=0;
for(int i=0;i<=up;i++)
{
b[pos]=i;
if(lead==1&&i==0) //前导0
{
tmp+=dfs(pos-1,s-1,sta,lead,limit&&i==up);
}
else
{
if(sta&&pos<(s+1)/2)//草稿纸看看
//枚举后半段
tmp+=dfs(pos-1,s,b[s-pos]==i,lead && i==0,limit&&i==up);
else //填充前半段
tmp+=dfs(pos-1,s,sta,lead && i==0,limit&&i==up);
}
}
if(!limit&&!lead)
dp[pos][s][sta]=tmp;
return tmp;
}
ll solve(ll x)
{
int pos=0;
while(x)
{
a[pos++]=x%10;
x/=10;
}
return dfs(pos-1,pos-1,1,true,true);//注意sta一开始要初始化为1,找了好久,因为无也是个回文字符串
}
int main()
{
memset(dp,-1,sizeof(dp));
int T;
cin>>T;
for(int i=1;i<=T;i++)
{
ll n,m;
scanf("%lld%lld",&n,&m);
if(n>m) swap(n,m);
printf("Case %d: %lld\n",i,solve(m)-solve(n-1));
}
return 0;
}