X mod f(x) HDU - 4389 数位DP

Here is a function f(x):
   int f ( int x ) {
    if ( x == 0 ) return 0;
    return f ( x / 10 ) + x % 10;
   }

Now, you want to know, in a given interval [A, B] (1 <= A <= B <= 10 9), how many integer x that mod f(x) equal to 0.
Input
   The first line has an integer T (1 <= T <= 50), indicate the number of test cases.
   Each test case has two integers A, B.
Output
   For each test case, output only one line containing the case number and an integer indicated the number of x.
   
Sample Input
2
1 10
11 20

Sample Output
Case 1: 10
Case 2: 3

题意:对于给定区间[A,B],求区间中满足x%f(x)=0的数的个数。

思路:f(x)最小为1,最大为81,我们可以枚举f(x)为mod,并设dp[pos][mod][sum][remain],表示pos位数中对mod取模余数为remain且数位和为sum的数的个数。易知mod=sum且remain=0时该数满足条件。

#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
int dp[12][82][82][82],dit[20];
int dfs(int pos,int mod,int sum,int remain,int limit)
{
	if(pos<0)
	{
		return remain==0&&sum==mod;
	}
	if(!limit&&dp[pos][mod][sum][remain]!=-1) return dp[pos][mod][sum][remain];
	int up=limit?dit[pos]:9;
	int ans=0;
	for(int i=0;i<=up;i++)
	{
		ans+=dfs(pos-1,mod,sum+i,(remain*10+i)%mod,limit&&i==dit[pos]);
	}
	if(!limit) dp[pos][mod][sum][remain]=ans;
	return ans;
}
int solve(int x)
{
	int len=0;
	int ans=0;
	while(x)
	{
		dit[len++]=x%10;
		x/=10;
	}
	for(int i=1;i<=81;i++)
		ans+=dfs(len-1,i,0,0,1);
	return ans;
}
int main()
{
	int n,m;
	int t,cas=1;
	cin>>t;
	memset(dp,-1,sizeof(dp));
	while(t--)
	{
		cin>>n>>m;
		
		cout<<"Case "<<cas++<<": "<<solve(m)-solve(n-1)<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值