ural 1057. Amount of Degrees (b进制数位dp)

题目链接 题意:设条件A为一个数恰好是k个互不相同的b的整数次幂的和,问某一个区间内满足条件A的数的个数是有多少个。

Example. Let X=15, Y=20, K=2, B=2. By this example 3 numbers are the sum of exactly two integer degrees of number 2:

17 = 24+20, 18 = 24+21, 20 = 24+22.

思路:数位dp..需要理解清楚恰好有k个b的互不相同的整数次幂的和这句话。

如果恰好是b的整数幂。。可以转化成b进制。。

互不相同。。说明。。所有位置上的数字要么是0,要么是1.

于是题目可以转化成求某区间内,满足一个数的b进制中恰好有k个1,其余都是0的数的个数有多少个。

然后就是数位dp的套路了。。。

注意dp数组的大小。。。应该按照位数最多的2进制考虑。。。一开始是按照10进制考虑结果只开了dp[15][15]….简直蠢哭。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年03月18日 星期五 12时13分55秒
 4File Name :code/ural//1057.cpp
 5************************************************ */
 6
 7#include <cstdio>
 8#include <cstring>
 9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25#define pi pair < int ,int >
26#define MP make_pair
27
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33int l,r;
34int k,base;
35int digit[700];
36int dp[700][700];
37
38
39int dfs( int pos , int cnt, bool limit)
40{
41    if (pos==0) return cnt==0;
42    if (cnt<0) return 0;
43
44    if (!limit&&dp[pos][cnt]!=-1) return dp[pos][cnt];
45
46    int mx = limit?digit[pos]:1;
47   // int mx = 1;
48    int res = 0 ;
49    for ( int i = 0 ; i <= mx ; i ++)
50    {
51	if (i>1) continue;
52	res += dfs(pos-1,i==1?cnt-1:cnt,limit&&i==mx);
53    }
54    return limit?res:dp[pos][cnt] = res;
55}
56int solve(int n )
57{
58    ms(digit,0);
59    int len = 0 ;
60    while (n)
61    {
62	digit[++len] = n % base;
63	n/=base;
64    }
65
66    return dfs(len,k,true);
67}
68int main()
69{
70	#ifndef  ONLINE_JUDGE 
71	freopen("code/in.txt","r",stdin);
72	 #endif
73//	ios::sync_with_stdio(false);
74	ms(dp,-1);
75	cin>>l>>r;
76	cin>>k>>base;
77//	cout<<"solve(r):"<<solve(r)<<" solve(l-1):"<<solve(l-1)<<endl;
78	int ans = solve (r) - solve (l-1);
79	cout<<ans<<endl;
80
81  #ifndef ONLINE_JUDGE 
82  fclose(stdin);
83  #endif
84    return 0;
85}