HDU

Palindrome Function

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=Lrj=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.

InputThe 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. 
(1T105,1LR109,2lr361≤T≤105,1≤L≤R≤109,2≤l≤r≤36)OutputFor 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



[l,r]在[kl,kr]进制下回文串个数。



#include<bits/stdc++.h>
#define MAX 100
using namespace std;
typedef long long ll;

int a[MAX];
int b[MAX];
ll dp[MAX][MAX][2][40];

ll dfs(int pos,int pre,bool hw,bool limit,int k){
    int i;
    if(pos<0){
        if(hw) return k;
        return 1;
    }
    if(!limit&&dp[pos][pre][hw][k]>-1) return dp[pos][pre][hw][k];
    int up=limit?a[pos]:k-1;
    ll cnt=0;
    for(i=0;i<=up;i++){
        b[pos]=i;
        if(pos==pre&&i==0){
            cnt+=dfs(pos-1,pre-1,hw,limit&&i==a[pos],k);
        }
        else if(hw&&pos<=pre/2){
            cnt+=dfs(pos-1,pre,hw&&b[pre-pos]==i,limit&&i==a[pos],k);
        }
        else{
            cnt+=dfs(pos-1,pre,hw,limit&&i==a[pos],k);
        }
    }
    if(!limit) dp[pos][pre][hw][k]=cnt;
    return cnt;
}
ll solve(ll x,int k){
    int pos=0;
    while(x){
        a[pos++]=x%k;
        x/=k;
    }
    return dfs(pos-1,pos-1,true,true,k);
}
int main()
{
    int tt=0,t,i;
    ll l,r,kl,kr;
    scanf("%d",&t);
    memset(dp,-1,sizeof(dp));
    while(t--){
        scanf("%lld%lld%lld%lld",&l,&r,&kl,&kr);
        ll ans=0;
        for(i=kl;i<=kr;i++){
            ans+=solve(r,i)-solve(l-1,i);
        }
        printf("Case #%d: %lld
",++tt,ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/yzm10/p/9531094.html