URAL 1057. Amount of Degrees (数位DP)

来源:互联网 发布:centos源码 编辑:程序博客网 时间:2024/05/16 01:56

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

inputoutput
15 2022
3


题目大意:
求给定区间[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代码:
#include <stdio.h>#include <cstring>#include <vector>#include <algorithm>#include <string.h>using namespace std;int digit[33];typedef long long LL;const int N = 50;int f[N][N]; //f[i][j]表示前i个中选 j 个 1的个数void init(){    f[0][0] =  1;    for(int i=1;i<33;i++){        f[i][0] = f[i-1][0];        for(int j=1;j<=i;j++)        {        f[i][j] = f[i-1][j] + f[i-1][j-1]; }                 }}int solve(int x,int k,int B){int len=-1;    //vector<int> v;    while(x)    {    digit[++len]=x%B;         //v.push_back(x%B);        x/=B;    }    int cnt = 0,ans = 0;    for(int i=len;i>=0;i--)    {        if(digit[i]==1) // 如果为 1,则依次求解        {            ans+=f[i][k-cnt]; //need             cnt++;            if(cnt==k)                break;        }        else if(digit[i]>1) //假如大于1的话,相当于所有的位可以为 1,所以直接求解跳出        {            ans += f[i+1][k-cnt];            break;        }    }    if(cnt==k)        ans++;    return ans;}int main(){    init();    int x,y,k,B;    while(~scanf("%d%d%d%d",&x,&y,&k,&B))    {        printf("%d\n",solve(y,k,B)-solve(x-1,k,B));    }    return 0;}



1 0
原创粉丝点击