Palindrome Function
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 256000/256000 K (Java/Others)
Total Submission(s): 431 Accepted Submission(s): 230
Problem 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
Source
2017中国大学生程序设计竞赛 - 网络选拔赛
题目大意:给出一个数字区间
[L,R]
和一个进制区间
[l,r]
,定义函数
f(n,k)
,若数字
n
在
解题思路:这道题跟LightOJ-1205和SPOJ-MYQ10 - Mirror Number很像,利用数位dp。
dp[i][j][k][r]
表示
k
进制下从
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN=40;
typedef long long LL;
int tmp[MAXN],num[MAXN];
int dp[MAXN][MAXN][MAXN][2];
//dp[i][j][k][r]:k进制下从i位到j为,状态为r(1表示回文)时回文数的个数
int dfs(int st,int cur,int pal,int limit,int base)
{
if(cur<0) return pal;
if(!limit&&dp[st][cur][base][pal]!=-1)
return dp[st][cur][base][pal];
int up=limit?num[cur]:(base-1);
int ans=0;
for(int i=0;i<=up;i++)
{
tmp[cur]=i;
if(st==cur&&i==0)
ans+=dfs(st-1,cur-1,pal,limit&&i==limit,base);
else if(pal&&cur<(st+1)/2)
ans+=dfs(st,cur-1,tmp[st-cur]==i,limit&&i==up,base);
else ans+=dfs(st,cur-1,pal,limit&&i==up,base);
}
if(!limit) dp[st][cur][base][pal]=ans;
return ans;
}
int calc(LL n,int base)
{
int len=0;
while(n)
{
num[len++]=n%base;
n/=base;
}
//num[len]=0;
return dfs(len-1,len-1,1,1,base);
}
int main()
{
memset(dp,-1,sizeof(dp));
int T;
scanf("%d",&T);
int cas=0;
while(T--)
{
LL L,R;
scanf("%lld%lld",&L,&R);
if(L>R) swap(L,R);
LL ans=0;
printf("Case %d: %d\n",++cas,calc(R,10)-calc(L-1,10));
}
return 0;
}