# HDU6156 Palindrome Function[数位DP]

## Palindrome Function

HDU - 6156

T_T 一开始我还傻傻的以为自己算错算错，其实只是算了回文数的个数。

#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
using namespace std;
typedef long long ll;
const int M=40;
ll dp[M][M][M][2];
int num[M],tmp[M];
ll dfs(int pos,int k,int cnt,bool state,bool limit)
{
if (pos==-1)
return state;
if (!limit && dp[k][pos][cnt][state]!=-1)
return dp[k][pos][cnt][state];
int up=limit?num[pos]:k-1;
ll res=0;
for (int i=0 ; i<=up ; ++i)
{
tmp[pos]=i;
if (pos==cnt && !i)
res+=dfs(pos-1,k,cnt-1,state,limit && i==num[pos]);
else if (state && pos<(cnt+1)/2)
res+=dfs(pos-1,k,cnt,i==tmp[cnt-pos],limit && i==num[pos]);
else
res+=dfs(pos-1,k,cnt,state,limit && i==num[pos]);
}
if (!limit)
dp[k][pos][cnt][state]=res;
return res;
}
ll solve(int x,int k)
{
int pos=0;
while (x)
{
num[pos++]=x%k;
x/=k;
}
ll ans=dfs(pos-1,k,pos-1,1,1);
return ans;
}
int main()
{
memset(dp,-1,sizeof(dp));
int T;
scanf("%d",&T);
for (int test=1 ; test<=T ; ++test)
{
int L,R,l,r;
scanf("%d%d%d%d",&L,&R,&l,&r);
ll ans=0;
for (int i=l ; i<=r ; ++i)
{
ll rn=solve(R,i);
ll ln=solve(L-1,i);
ans+=(rn-ln)*i;
ans+=(R-rn-(L-1-ln));
}
printf("Case #%d: %lld\n",test,ans);
}
return 0;
}