X mod f(x)
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 <= 109), 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
题解:数位DP经典题,这里不同的是我这里的和是不同的,那么9个位置9*9就是81,那么和最多到81,枚举和就行了,不过这里要开4维,因为多一维表示现在要求的和,代码里面解释的很清楚哦~~~
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<map>
#include<cmath>
#include<stack>
#define LL long long
using namespace std;
int t,x,y;
int a[20],f[10][82][82][82];//第多少项,余数,前面num项和,要达到的和
//心态炸了,数组不能开太大了啊,只能开到这里,再看直接MLE或者WA了
//最开始状态转移方程是f[num][mod][sum]的,但是后来发现,必须要加上一个[m]才可以,因为可能这种f[num][mod][sum]刚好之前也有这种情况,但此时的m是不同的,所以会WA
// 其余的就都是套模板了啦
int dfs(int num,int mod,int sum,int limit,int m)
//位数,上一位,总的f(x)
{
int ans=0,up;
if(num==0)return (sum==m)&&(mod==0);
if(!limit&&f[num][mod][sum][m]!=-1)return f[num][mod][sum][m];
if(!limit)up=9;
else up=a[num];
for(int i=0;i<=up;i++)
{
int mod_x=(mod*10+i)%m;
ans+=dfs(num-1,mod_x,sum+i,limit&&i==a[num],m);
}
if(!limit)f[num][mod][sum][m]=ans;
return ans;
}
int slove(int x)
{
int num=0,sum=0;
if(x<=0)return 0;
while(x!=0)
{
a[++num]=x%10;
x/=10;
}
for(int i=1;i<=81;i++)//总共有9位,每位顶多为9,所以是1~9*9
{
sum+=dfs(num,0,0,1,i);
}
return sum;
}
int main()
{
int pos=0;
scanf("%d",&t);
memset(f,-1,sizeof(f));
memset(a,0,sizeof(a));//初始化必须放在外面,因为有的时候有相同的情况就可以不用搜了,否则会T
for(int i=1;i<=t;i++)
{
scanf("%d%d",&x,&y);
printf("Case %d: ",++pos);
printf("%d\n",slove(y)-slove(x-1));
}
}