您的位置:首页 > 其它

LightOJ 1068 Investigation (数位DP)

2016-08-08 11:21 316 查看
题意求出区间[A,B]内能被K整除且各位数字之和也能被K整除的数的个数。

分析:[b]A,B最多有10位   
各位数字之和不会超过90,那么当 k >= 90时,为0.[/b]

[b]dp[len][y1][y2]    第len位   y1这个数除k的余数  y2位各个位和除k的余数.[/b]





#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<cctype>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<iomanip>
#include<sstream>
#include<limits>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N= 2000;
const int maxn = 1e3+10;
const int maxm = 2000000001;
const int MOD = 1000;
int dp[20][100][100],k,dig[maxn];
int dfs(int len ,int y1, int y2, int ok)
{
if (len == 0) return y1 == 0 && y2 == 0;
if(!ok && dp[len][y1][y2] != -1) return dp[len][y1][y2];
int ans = 0, res = ok? dig[len]:9; //如果上一位到最大的数则这一位不能取9.
for(int i = 0; i <= res; i++)
ans += dfs(len-1,(y1*10+i) % k,(y2+i)%k,ok && i==res);
if (!ok) dp[len][y1][y2] = ans; //这一位到了最大数,则不能赋值,因为不能为后面所用。
return ans;
}
int work(int n)
{
int cnt = 1;
while(n)
{
dig[cnt++] = n %10;
n /= 10;
}
return dfs(cnt-1,0,0,1);
}
int main(){
#ifdef LOCAL
freopen("C:\\Users\\lanjiaming\\Desktop\\acm\\in.txt","r",stdin);
//freopen("output.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
int T,kase = 0;
cin>>T;
while(T--)
{
cout<<"Case "<<++kase<<": ";
int a,b;
cin>>a>>b>>k;
if (k > 90)
{
cout<<0<<endl;
continue;
}
memset(dp,-1,sizeof(dp));
cout<<work(b) - work(a-1)<<endl;
}
return 0;
}






内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lightoj ACM 动态规划