1057. Amount of Degrees
Time limit: 1.0 second
Memory limit: 64 MB
Create a code to determine the amount of integers, lying in the set [X;Y] and being a sum of exactlyK 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 = 24+20,
18 = 24+21,
20 = 24+22.
Input
The first line of input contains integers X and Y, separated with a space (1 ≤ X ≤ Y ≤ 231−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 |
题目大意:
求给定区间[X,Y]中满足下列条件的整数个数: 这个数恰好等于K个互不相等的B的整数次幂之和。例如,设X=15,Y=20,K=2,B=2,则有且仅有下列三个数满足题意:
17 = 2^4+2^0,
18 = 2^4+2^1,
20 = 2^4+2^2.
1 ≤ X ≤ Y ≤ 2^31−1,1 ≤ K ≤ 20, 2 ≤ B ≤ 10。
实质上:求[X,Y] 区间转化为 B 进制 1 的个数为K 的数的出现次数。
题解:数位DP。
注意:只有系数为1的情况,所以每位只能是0,1,至于不相同的只要是取1 的时候不不相同,至于0是不变的。
大体思路:
所求的数为互不相等的幂之和,亦即其B进制表示的各位数字都只能是0和1。
因此,我们只需讨论二进制的情况,其他进制都可以转化为二进制求解。
本题区间满足区间减法,因此可以进一步简化问题:令count[i..j]表示[i..j]区间内合法数的个数,则
count[i..j]=count[0..j]-count[0..i-1]。
换句话说,给定n,我们只需求出从0到n有多少个符合条件的数。
步骤:
首先预处理f。
f[i,j]代表i位二进制数中恰好有j个1的数的个数。
f[i,j]=f[i-1,j]+f[i-1,j-1]
计算count[0..n]
像前几题一样,一位一位枚举,只需要多记录后面需要的1的个数即可。
if digit[i] = 1 then ans = ans + f[i,need]
need就是后面需要的1的个数。
AC代码: