题意:
已知函数f(x, k),如果10进制数x在k进制下是个回文数,那么f(x, k)值为k,否则为1。现给出L, R, l, r, 求出∑∑f(i, j) 其中(L<=i<=R)(l<=j<=r)
思路:
枚举每个进制,然后进行数位dp就好了,原本想少写点开个二维,但是没法记忆化了,就跟暴搜一样了= =,于是开了个思维。
dp[pos][i][j][k]表示第pos位i进制下回文串长度为j且字符串其上一位为k时候的记忆化值。
代码:
#include <bits/stdc++.h>
#define LL long long
using namespace std;
int L, R, l, r;
int wei[65], now[65];
LL dp[65][40][40][40];
LL dfs(int pos, int limit, int lead, int bas, int len, int ft)
{
if(pos == -1) return 1;
if(!limit && !lead && dp[pos][bas][len][ft] != -1) return dp[pos][bas][len][ft];
int up = limit? wei[pos]: bas-1;
LL tmp = 0;
for(int i = 0; i <= up; ++i)
{
if(lead && i == 0) tmp += dfs(pos-1, limit&&i==wei[pos], 1, bas, 39, 39);
else
{
if(lead)
{
now[1] = i;
tmp += dfs(pos-1, limit&&i==wei[pos], 0, bas, pos+1, i);
}
else
{
if(len-pos <= len/2)
{
now[len-pos] = i;
tmp += dfs(pos-1, limit&&i==wei[pos], 0, bas, len, ft);
}
else if(len&1 && len-pos-1 == len/2)
{
tmp += dfs(pos-1, limit&&i==wei[pos], 0, bas, len, ft);
}
else if(len-pos > len/2)
{
if(now[pos+1] != i) continue;
tmp += dfs(pos-1, limit&&i==wei[pos], 0, bas, len, ft);
}
}
}
}
if(!limit && !lead) dp[pos][bas][len][ft] = tmp;
return tmp;
}
LL work(LL x, int bas)
{
int pos = 0;
while(x)
{
wei[pos++] = x%bas;
x /= bas;
}
return dfs(pos-1, 1, 1, bas, 39, 39);
}
int main()
{
memset(dp, -1, sizeof dp);
int t; scanf("%d", &t);
for(int _ = 1; _ <= t; ++_)
{
LL tmp, ans = 0;
scanf("%d %d %d %d", &L, &R, &l, &r);
for(int i = l; i <= r; ++i)
{
tmp = work(R, i)-work(L-1, i);
ans += tmp*i + (R-L+1-tmp);
}
printf("Case #%d: %lld\n", _, ans);
}
return 0;
}
继续加油~