HDU-6156 Palindrome Function(数位DP)

题意:

已知函数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;
}


继续加油~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值