标签:lse i++ pre dfs 枚举 turn += c++ cstring
原题链接
考察:数位dp
思路:
??求回文数字的个数.
??dfs参数:
1.pos 枚举到第几位
2.len 回文数的长度.
??其实不需要变量记录是否合法,不合法的不取搜就行了.
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 20;
LL l,r,f[N][N];
int a[N],nums[N];
LL dfs(int pos,int len,bool limit,bool lead)
{
if(!pos) return 1;
if(!limit&&!lead&&~f[pos][len]) return f[pos][len];
int up = limit?a[pos]:9;
LL res = 0;
for(int i=0;i<=up;i++)
{
if(!i&&lead) res+=dfs(pos-1,len,limit&&i==up,lead&&!i);
else{
nums[pos] = i;
if(lead) res+=dfs(pos-1,pos,limit&&i==up,lead&&!i);
else if(pos>=len/2+1) res+=dfs(pos-1,len,limit&&i==up,lead&&!i);
else if(i==nums[len+1-pos]) res+=dfs(pos-1,len,limit&&i==up,lead&&!i);
}
}
if(!limit&&!lead) f[pos][len] = res;
return res;
}
LL dp(LL n)
{
if(!n) return 1;
int cnt = 0;
while(n) a[++cnt] = n%10,n/=10;
return dfs(cnt,0,1,1);
}
int main()
{
int T,kcase = 0;
scanf("%d",&T);
memset(f,-1,sizeof f);
while(T--)
{
scanf("%lld%lld",&l,&r);
if(l>r) swap(l,r);
printf("Case %d: %lld\n",++kcase,dp(r)-dp(l-1));
}
return 0;
}
Palindromic Numbers LightOJ - 1205
标签:lse i++ pre dfs 枚举 turn += c++ cstring
原文地址:https://www.cnblogs.com/newblg/p/14835332.html