Description
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
input | output |
---|---|
15 20 2 2 | 3 |
论文题
- 这种统计方法,从画出来的树来看是从左往右统计一次且仅一次,文章中这样描述这种统计方法"对于询问 n,我们找到一个等于 1 的数位,将它赋为 0,则它右面的数位可以任意取,我们需要统计其中恰好含有 K-tot 个 1 的数的个数(其中 tot 表示这一位左边的 1 的个数),则可以利用组合数公式求解。逐位枚举所有”1”进行统计即可。" 这句话中右边的数位可以任意取说的就是可以去高度为h-1的树中任意找,因为这棵树中的每个数只要它1的个数符合要求就都可以取来,也就是组合数Cn(k-tot).
- 如果这个数本身就是有K个1,要特别得给答案加1
/*************************************************************************
> File Name: Newural1057.cpp
> Author:HaoWei
> Mail:liang199611@outlook.com
> Created Time: 2016年07月02日 星期六 15时03分36秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define beZero(a) memset(a,0,sizeof(a))
int f[33][22],X,Y,K,B;
int solve(int x)
{
int tot=0,kount=0,res=0,num[33],temp=x;
beZero(num);
while(temp) num[kount]=temp%B,kount++,temp/=B;
for(int i=kount-1;i>=0;i--)
{
if(num[i]>1)
{
res+=f[i+1][K-tot];
break;
}
else if(num[i]==1)
{
if(K-tot<0) break;
res+=f[i][K-tot];
x-=(1<<i);
// printf("debug:f%d ",f[i][K-tot]);
tot++;
}
}
if((tot+x)==K) res++;
return res;
}
int main()
{
beZero(f);
rep(i,32) f[i][0]=1;
for(int i=1;i<33;i++) for(int j=1;j<22;j++) f[i][j]=f[i-1][j-1]+f[i-1][j];
// printf("f[4][2]:%d\n",f[4][2]);
scanf("%d%d%d%d",&X,&Y,&K,&B);
X--;
solve(Y);
cout<<solve(Y)-solve(X)<<endl;
return 0;
}