hdu 3967 Zero's Number (不允许前导0(新写法)的数位dp)
题意:给出l,r,k,定义f(n,k)为将数n分成左右两个非空的部分,再求和之后能被k整除的方案数。
现在问区间[l,r]中所有f(i,k)的和。
思路:数位dp...
枚举一下分点即可。。想到这个这题就A了。。。
然后相当于做分点个数个数位dp...求和即可。
dp[i][j][k][p]表示第i位,前半部分%k的结果,后半部分%k的结果,是否有前导0.
然后关于前导0这个。。。换了一种写法。。。加了一个状态在dp数组里。。。
不然每次都要一个if。。。感觉有点丑。。。。这样写简介了一点。。。
以及。。因为每次k是不同的。。。我dp状态记录的时候又没有记录k...所以记得每次初始化成-1。。。
因为忘记这个结果第二个样例调了好久一直是31。。。。
1/* ***********************************************
2Author :111qqz
3Created Time :Thu 29 Sep 2016 02:49:50 PM CST
4File Name :code/hdu/3967.cpp
5************************************************ */
6#include <cstdio>
7#include <cstring>
8#include <iostream>
9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <set>
13#include <map>
14#include <string>
15#include <cmath>
16#include <cstdlib>
17#include <ctime>
18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedef long long LL;
24#define pi pair < int ,int >
25#define MP make_pair
26using namespace std;
27const double eps = 1E-8;
28const int dx4[4]={1,0,0,-1};
29const int dy4[4]={0,-1,1,0};
30const int inf = 0x3f3f3f3f;
31int k;
32LL l,r;
33int digit[20];
34LL dp[20][20][20][20][2];
35LL dfs( int pos,LL sum1,LL sum2,bool limit,int cut,int prehasnonzero)
36{
37 if (pos==0) return (sum1+sum2)%k==0;
38 if (!limit&&dp[pos][sum1%k][sum2%k][cut][prehasnonzero]!=-1) return dp[pos][sum1%k][sum2%k][cut][prehasnonzero];
39 int mx = limit?digit[pos]:9;
40 LL res = 0 ;
41 for ( int i = 0 ; i <= mx; i++)
42 {
43 if (pos<cut) res = res + dfs(pos-1,sum1,sum2*10+i,limit&&i==mx,cut,prehasnonzero||i!=0);
44 else
45 {
46 if (!prehasnonzero&&pos==cut&&i==0) continue; //前半部分可以有前导0,但是不能全为0.
47 res = res + dfs(pos-1,sum1*10+i,sum2,limit&&i==mx,cut,prehasnonzero||i!=0);
48 }
49 }
50 if (!limit) dp[pos][sum1%k][sum2%k][cut][prehasnonzero] = res;
51 return res;
52}
53LL solve( LL n)
54{
55 // if (n<10) return 0;
56 ms(digit,0);
57 int len = 0 ;
58 ms(dp,-1);// 每次计算的时候都要初始化dp。。。因为d不一样。。。。。。
59 while (n)
60 {
61 digit[++len] = n % 10;
62 n /= 10;
63 }
64 LL res = 0 ;
65 for ( int i = 2 ; i <= len ; i++)
66 res = res + dfs(len,0,0,true,i,0);
67 return res;
68}
69int main()
70{
71 #ifndef ONLINE_JUDGE
72 freopen("code/in.txt","r",stdin);
73 #endif
74 while (~scanf("%lld%lld%d",&l,&r,&k))
75 {
76 LL ans = solve(r) - solve(l-1);
77 printf("%lld\n",ans);
78 }
79 #ifndef ONLINE_JUDGE
80 fclose(stdin);
81 #endif
82 return 0;
83}