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

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4389点击打开链接

X mod f(x)

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3373    Accepted Submission(s): 1318


Problem Description
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
 

Author
WHU
 

Source
 

Recommend
zhuyuanchen520
 

刚学没多久数位dp 

这道题因为看错题意加上状态量比较多耽搁了好久 就记录发

一开始没注意看函数以为是求数字根 其实是求各位数字之和

我们用dp[pos][sum][x][mod]来表示 第pos位之前各位数字之和为sum的数 除以x(也就是题意中的f(x))的余数为mod

那么终止条件就是当pos枚举到0时 判断枚举的这个数是否满足数字之和为sum并且他的余数为0 

转移就是

dp[pos][sum][x][mod]=dp[pos-1][sum+i][x][(mod*10+i)%x]

然后我们对于每一个需要cal的数 枚举各位数加起来的81种情况即可

剩下的按数位dp模板套就行

扫描二维码关注公众号,回复: 2484887 查看本文章
#include<bits/stdc++.h>
using namespace std;
int dp[10][81][81][81];
int bit[10];
int dfs(int pos,int sum,int x,int mod,int flag)
{
    if(pos==0)
        {
            return x==sum&&mod==0;
        }
    if(flag&&dp[pos][sum][x][mod]!=-1)
        return dp[pos][sum][x][mod];
    int up=flag?9:bit[pos];
    int ans=0;
    for(int i=0;i<=up;i++)
    {
        ans+=dfs(pos-1,sum+i,x,(mod*10+i)%x,flag||i<up);
    }
    if(flag)
    {
        dp[pos][sum][x][mod]=ans;
    }
    return ans;
}
int cal(int x)
{
    int len=0;
    while(x)
    {
        bit[++len]=x%10;
        x/=10;
    }
    int ans=0;
    for(int i=1;i<=81;i++)
    {
        ans+=dfs(len,0,i,0,0);
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    memset(dp,-1,sizeof(dp));
    for(int cnt=1;cnt<=t;cnt++)
    {
        int l,r;
        scanf("%d%d",&l,&r);
        printf("Case %d: %d\n",cnt,cal(r)-cal(l-1));
    }
}




猜你喜欢

转载自blog.csdn.net/xuejye/article/details/80006187