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************************************************ */
 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;
6int l,r;
7int k,base;
8int digit[700];
9int dp[700][700];
1int dfs( int pos , int cnt, bool limit)
2{
3    if (pos==0) return cnt==0;
4    if (cnt<0) return 0;
    if (!limit&&dp[pos][cnt]!=-1) return dp[pos][cnt];
 1    int mx = limit?digit[pos]:1;
 2   // int mx = 1;
 3    int res = 0 ;
 4    for ( int i = 0 ; i <= mx ; i ++)
 5    {
 6	if (i>1) continue;
 7	res += dfs(pos-1,i==1?cnt-1:cnt,limit&&i==mx);
 8    }
 9    return limit?res:dp[pos][cnt] = res;
10}
11int solve(int n )
12{
13    ms(digit,0);
14    int len = 0 ;
15    while (n)
16    {
17	digit[++len] = n % base;
18	n/=base;
19    }
 1    return dfs(len,k,true);
 2}
 3int main()
 4{
 5	#ifndef  ONLINE_JUDGE 
 6	freopen("code/in.txt","r",stdin);
 7	 #endif
 8//	ios::sync_with_stdio(false);
 9	ms(dp,-1);
10	cin>>l>>r;
11	cin>>k>>base;
12//	cout<<"solve(r):"<<solve(r)<<" solve(l-1):"<<solve(l-1)<<endl;
13	int ans = solve (r) - solve (l-1);
14	cout<<ans<<endl;
1  #ifndef ONLINE_JUDGE 
2  fclose(stdin);
3  #endif
4    return 0;
5}