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

来源:互联网 发布:java m5解密 编辑:程序博客网 时间:2024/05/29 04:42

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;}
原创粉丝点击