As we all know,a palindrome number is the number which reads the same backward as forward,such as 666 or 747.Some numbers are not the palindrome numbers in decimal form,but in other base,they may become the palindrome number.Like 288,it’s not a palindrome number under 10-base.But if we convert it to 17-base number,it’s GG,which becomes a palindrome number.So we define an interesting function f(n,k) as follow:
f(n,k)=k if n is a palindrome number under k-base.
Otherwise f(n,k)=1.
Now given you 4 integers L,R,l,r,you need to caluclate the mathematics expression ∑Ri=L∑rj=lf(i,j)∑i=LR∑j=lrf(i,j) .
When representing the k-base(k>10) number,we need to use A to represent 10,B to represent 11,C to repesent 12 and so on.The biggest number is Z(35),so we only discuss about the situation at most 36-base number.
Input
The first line consists of an integer T,which denotes the number of test cases.
In the following T lines,each line consists of 4 integers L,R,l,r.
(1≤T≤105,1≤L≤R≤109,2≤l≤r≤361≤T≤105,1≤L≤R≤109,2≤l≤r≤36)
Output
For each test case, output the answer in the form of “Case #i: ans” in a seperate line.
Sample Input
3
1 1 2 36
1 982180 10 10
496690841 524639270 5 20
Sample Output
Case #1: 665
Case #2: 1000000
Case #3: 447525746
开了三维的状态 第一个代表当前位置,第二个代表进制,第三个代表开始的位置
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll dp[40][40][40];
int an[40],wei[40];
ll dfs(int pos,int zero,int jin,int flag,int be)
{
if(pos<0) return zero==0;
if(dp[pos][jin][be]!=-1&&!flag&&!zero) return dp[pos][jin][be];
ll res=0;
int up=flag?wei[pos]:jin-1;
for(int i=0;i<=up;i++)
{
if(zero&&i==0) res+=dfs(pos-1,zero,jin,flag&&i==up,be);
else{
if(zero)
{
an[pos]=i;
res+=dfs(pos-1,0,jin,flag&&i==up,pos);
}
else if(pos<(be+1)/2)
{
if(i==an[be-pos])
res+=dfs(pos-1,0,jin,flag&&i==up,be);
}
else{
an[pos]=i;
res+=dfs(pos-1,0,jin,flag&&i==up,be);
}
}
}
an[pos]=-1;
if(!flag&&!zero)
{
dp[pos][jin][be]=res;
}
return res;
}
ll solve(int x,int jin)
{
int len=0;
while(x)
{
wei[len++]=x%jin;
x/=jin;
}
return dfs(len-1,1,jin,1,39);
}
int main()
{
int t;
scanf("%d",&t);
memset(dp,-1,sizeof(dp));
int cas=1;
while(t--)
{
int l,r,L,R;
scanf("%d%d%d%d",&l,&r,&L,&R);
ll tol=0;
for(int i=L;i<=R;i++)
{
ll ret=solve(r,i)-solve(l-1,i);
tol+=ret*i+(r-l+1-ret);
}
printf("Case #%d: %lld\n",cas++,tol );
}
}