hdu 3652 B-number (带整除的数位dp )
题目链接 题意:给出n,问[1,n]中,满足包含“13”且这个数(不是各位的和)能被13整除的数的个数。 思路:依然是数位dp..不过有一个小tip。。
由于包含13的情况非常难考虑(包含一个“13”,两个“13”.....)
所以要从反面考虑,即不包含13的情况。
但是由于还有另一个条件。
做法是把能被13整除的数考虑成全集U,然后在U中做分划,一部分是含13的,另一部分是不含13的。
这样我们要求两个答案,一个是能被13整除的,另一个是能被13整除并且不含13的,相减即为题目所求。
/* ***********************************************
Author :111qqz
Created Time :2016年03月16日 星期三 09时27分49秒
File Name :code/hdu/3652.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6LL n;
7LL dp[20][15];
8LL dp2[20][2][15];
9int digit[20];
1LL dfs (int pos,int sum,bool limit)
2{
3 if (pos==0) return sum==0;
if (!limit&&dp[pos][sum]!=-1) return dp[pos][sum];
int mx = limit ? digit[pos]:9;
1 LL res = 0LL ;
2 for ( int i = 0 ; i <= mx ; i++)
3 {
4 res+=dfs(pos-1,(sum*10+i),limit&&i==mx);
5 }
1 if(!limit) dp[pos][sum] = res;
2 return res;
3}
4LL dfs2(int pos,bool preis1,int sum,bool limit)
5{
6 if (pos==0) return sum==0;
if (!limit&&dp2[pos][preis1][sum]!=-1) return dp2[pos][preis1][sum];
1 int mx = limit? digit[pos]:9;
2 LL res = 0 ;
3 for ( int i = 0 ; i <= mx ; i++)
4 {
5 if (preis1&&i==3) continue;
6 res+=dfs2(pos-1,i==1,(sum*10+i),limit&&i==mx);
7 }
1 if (!limit) dp2[pos][preis1][sum] = res;
2 return res;
3}
1LL solve ( LL n)
2{
3 ms(digit,0);
1 int len = 0;
2 while (n)
3 {
4 digit[++len] = n;
5 n/= 10;
6 }
7 return dfs(len,0,true)-dfs2(len,false,0,true); //在能被13整除的数里划分,减去不含“13”的,就是含“13”的。
8 //因为含“13”的情况太复杂了。。。
9}
10int main()
11{
12 #ifndef ONLINE_JUDGE
13 freopen("code/in.txt","r",stdin);
14 #endif
1 ms(dp,-1); //dp数组子啊外面清空就好。。。。因为dp数组是所有数据公用的啊。。。。
2 ms(dp2,-1);
3 while (~scanf("%lld",&n))
4 {
5 LL ans = solve (n);
6 printf("%lld\n",ans);
7 }
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}