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;
}
本文介绍了一种算法,用于计算在给定区间[A,B]中,满足x%f(x)=0条件的整数数量。通过深度探讨f(x)函数特性,采用动态规划方法,枚举f(x)作为模数,设计四维状态转移方程,高效解决了问题。

261

被折叠的 条评论
为什么被折叠?



