1057. Amount of Degrees
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
Create a code to determine the amount of integers, lying in the set [
X;
Y] and being a sum of exactly
K different integer degrees of
B.
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 = 2
4+2
0,
18 = 2 4+2 1,
20 = 2 4+2 2.
18 = 2 4+2 1,
20 = 2 4+2 2.
Input
The first line of input contains integers
X and
Y, separated with a space (1 ≤
X ≤
Y ≤ 2
31−1). The next two lines contain integers
K and
B (1 ≤
K ≤ 20; 2 ≤
B ≤ 10).
Output
Output should contain a single integer — the amount of integers, lying between
X and
Y, being a sum of exactly
K different integer degrees of
B.
Sample
input | output |
---|---|
15 20 2 2 | 3 |
题目大意:给出区间[X,Y],给出K和B,求区间内有多少个数可以被拆分成不同的K个B的幂的和,例如17可以被拆成2^4+2^0等。
现在不妨把B看做进制,如果将满足条件的十进制数A转化为B进制,则一定包含K个1和Len-K个0。
于是我们设dp[pos][cnt]表示到第pos位,填放了cnt个1的方案数,然后做记忆化搜索即可。
至于为什么恰好为K个1,是因为拆分出的幂必须是互不相同的,也就是说不存某一位上的数大于1。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define MAXLEN 32
#define MAXNUM 10
#define INF 0x3f3f3f3f
typedef long long int LL;
int dp[MAXLEN+10][MAXLEN+5];
int Num[MAXLEN+10];
int Len;
int X,Y,K,B;
void GetNum(int x)
{
memset(Num,0,sizeof(Num));
Len=0;
while(x)
{
Num[++Len]=x%B;
x/=B;
}
return;
}
int dfs(int pos,int used,bool lim)
{
if(used>K)return 0;
if(pos<=0)return used==K;
if(!lim&&dp[pos][used]!=-1)
return dp[pos][used];
int Nmax,ans=0;
Nmax=lim?Num[pos]:B-1;
if(0<=Nmax)ans+=dfs(pos-1,used,lim&&0==Nmax);
if(1<=Nmax)ans+=dfs(pos-1,used+1,lim&&1==Nmax);
if(!lim)dp[pos][used]=ans;
return ans;
}
int GetAns(int x)
{
GetNum(x);
return dfs(Len,0,1);
}
int main()
{
memset(dp,-1,sizeof(dp));
scanf("%d%d%d%d",&X,&Y,&K,&B);
printf("%d\n",GetAns(Y)-GetAns(X-1));
}
/*
1 2
1 2
*/