您的位置:首页 > 其它

数位DP-URAL-1057-Amount of Degrees

2015-11-03 23:16 411 查看
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 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 = 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

15 20

2

2

3

Problem Source: Rybinsk State Avia Academy

题意:

给定一个区间[X,Y],求在这个区间内,等于整数B的K个不同次幂之和的数的个数。例如:K=2,B=2,X=15,Y=20。

17=2^4+2^0

18=2^4+2^1

20=2^4+2^2

那么该输出3.

这个题样例就给的二进制,稍微想一下就知道,二进制的情况是最简单的,只用求在转换为二进制之后,有K个1的数有多少个就行了。

比如17就是10001,有2个1;18是10010,有2个1;20是10100,有2个1。

那么就先来讨论如何解决二进制即B=2的情况。

首先是预处理,将32位内的情况先处理出来。

用dp
[num]表示前n位有num个1的数有多少个。

那么dp[i][j]=dp[i-1][j]+dp[i-1][j-1]。

然后由于题中要求的是[X,Y]内的情况,那么这个满足区间减法,用F(X)表示[1,X]内的满足条件的数的个数,那么要输出的就是F(Y)-F(X-1)。

对于F(X)值的获取:

先将X+1化为二进制存在num[]数组里,值sum=0,还需要的1的个数need=K,然后从最高位开始,如果当前位num[i]为1,那么sum+=dp[i-1][need],最后need– –,就这样一直处理到最后一位。

这其中的原理是,我们把已经处理过的位的数据作为前缀,当第i位为1时,先考虑前缀+(0~11…(i-1个1))内有多少种满足题意的数,那么就是加上dp[i-1][need],然后由于第i位为1,并且即将成为前缀,再考虑第i-1位时,前缀中的1+后i-1位的1一共和为K个1,所以need– –。

然而如果不是二进制,只用在转换为B进制之后,从最大位开始找,找到第一个比1大的位,将其后面全部置为1便可。

//
//  main.cpp
//  ural1057
//
//  Created by 袁子涵 on 15/11/3.
//  Copyright © 2015年 袁子涵. All rights reserved.
//
//  15ms    388KB

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <algorithm>

using namespace std;

int X,Y;
int dp[32][32];
int K,B;

void handle()
{
for (int i=2; i<32; i++) {
dp[i][0]=1;
for (int j=1; j<=i; j++) {
dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
}
}
}

int DP(int N)
{
int num[32],k=0,flag=-1,sum=0,need=K;
memset(num, 0, sizeof(num));
while (N) {
num[++k]=N%B;
N/=B;
}
if (B!=2) {
for (int i=k; i>0; i--) {
if (num[i]>1) {
flag=i;
break;
}
}
for (int i=flag; i>=0; i--) {
num[i]=1;
}
}
for (int i=k;i>0; i--) {
if (num[i]==1) {
sum+=dp[i-1][need--];
}
else
continue;
}
return sum;
}

int main(int argc, const char * argv[]) {
cin >> X >> Y;
cin >> K >> B;
dp[0][1]=0;
dp[0][0]=1;
dp[1][1]=1;
dp[1][0]=1;
handle();
Y=DP(Y+1);
X=DP(X);
cout << Y-X << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: