hdu 4398 X mod f(x)(数位DP)

Time limit2000 msMemory limit32768 kBOSWindows

ere 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的各个数位和被x整除的数有多少个?

分析:A,B的范围最大为10^9,那么数位和的最大值为81,因此可以枚举数位和
dp[pos][sum][rem][mod],pos代表当前的数位的个数,sum表示当前的数位和,rem代表取模后的余数,mod代表要取模的数
然后利用模板,转化为cal(b)-cal(a-1),记忆化搜索求解

#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <set>
#include <string>
using namespace std;
#define mem(a,n) memset(a,n,sizeof(a))
typedef long long LL;
const int N=1e3+5;
const int mod=1e9+7;
int dp[10][82][82][82],digit[10];
int dfs(int pos,int sum,int rem,int mod,bool bounded)
///pos代表当前的数位的个数,sum表示当前的数位和,rem代表取模后的余数,mod代表要取模的数,bounded为上界的标记
{
    if(pos==0) return sum==mod&&rem==0;///满足数位和为mod并且数位和整除mod
    int& ret=dp[pos][sum][rem][mod];
    if(!bounded&&ret!=-1) return ret;
    int end=bounded?digit[pos]:9;
    int ans=0;
    for(int i=0;i<=end;i++)
        ans+=dfs(pos-1,sum+i,(rem*10+i)%mod,mod,bounded&&i==end);
    if(!bounded) ret=ans;
    return ans;
}

int cal(int x)
{
    int len=0;
    while(x)
    {
        digit[++len]=x%10;
        x/=10;
    }
    int ans=0;
    for(int i=1;i<=81;i++)
        ans+=dfs(len,0,0,i,true);
    return ans;
}

int main()
{
    int T,cas=1;
    mem(dp,-1);
    scanf("%d",&T);
    while(T--)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        printf("Case %d: %d\n",cas++,cal(b)-cal(a-1));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值