Description
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) .
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≤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
核心思想:
预处理以下内容:
枚举每个进制z,再枚举z进制下的w位的数字,对称之后可得一个2*w位或者2*w+1位的回文数。将z进制下得到的回文数存至h[z]数组中,数量记为cnt[z]。
对于每次询问:
依次处理l~r进制,对于每个进制z,二分查找L和R在h[z]数组中的位置,可得满足f(n,z)=z的n的数量,其余的均=1。将各个进制下得到的ans相加即可。
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=160,M=2e5+20;
ll a[N];//每个数位上的数
int z,w,cnt[37];
bool yes;//枚举出的回文数大小是否超过上限1e9
ll h[37][M];//存枚举出的回文数
//将数位上的数对称成回文数
//f=1表示回文数有奇数位,=0表示为偶数位
ll fun(int f)
{
ll ans=0;
for(int i=1;i<=w;i++)
ans=ans*z+a[i];
if(!f)//偶数位多生效一个a[w]
ans=ans*z+a[w];
for(int i=w-1;i>0;i--)
ans=ans*z+a[i];
return ans;
}
//枚举每一个数位上数
void dfs(int k)
{
//递归出口
if(k>w)
{
ll t=fun(1);
if(t>1e9)
{
yes=1;
return;
}
h[z][cnt[z]++]=t;
t=fun(0);
if(t<=1e9)
h[z][cnt[z]++]=t;
return;
}
for(int i=0;i<z;i++)
{
a[k]=i;
dfs(k+1);
if(yes)
return;
}
return;
}
int getid(int k,ll x)
{
return lower_bound(h[k],h[k]+cnt[k],x)-h[k];
}
int main()
{
int T;
cin>>T;
for(z=2;z<=36;z++)
{
cnt[z]=0;
for(w=1;;w++)
{
for(int i=1;i<N;i++)
a[i]=0;
a[1]=1;
if(fun(1)>1e9)
break;
//首位不能为0,由于是回文数,则最低位也不能为0
for(int i=1;i<z;i++)
{
a[1]=i;
yes=0;
dfs(2);
}
}
}
//排序方便二分
for(int i=2;i<37;i++)
sort(h[i],h[i]+cnt[i]);
int ca=0;
while(T--)
{
ll ans=0,L,R;
int l,r;
scanf("%lld%lld%d%d",&L,&R,&l,&r);
for(int i=l;i<=r;i++)
{
int x=getid(i,L);
int y=getid(i,R+1);
ans+=(R-L+1)+(y-x)*(i-1);
}
printf("Case #%d: %lld\n",++ca,ans);
}
return 0;
}