F(x)

论坛 期权论坛 脚本     
匿名技术用户   2020-12-28 13:23   26   0

F(x)

Time Limit: 1000/500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5055 Accepted Submission(s): 1880


Problem Description
For a decimal number x with n digits (AnAn-1An-2 ... A2A1), we define its weight as F(x) = An * 2n-1 + An-1 * 2n-2 + ... + A2 * 2 + A1 * 1. Now you are given two numbers A and B, please calculate how many numbers are there between 0 and B, inclusive, whose weight is no more than F(A).

Input
The first line has a number T (T <= 10000) , indicating the number of test cases.
For each test case, there are two numbers A and B (0 <= A,B < 109)

Output
For every case,you should output "Case #t: " at first, without quotes. The t is the case number starting from 1. Then output the answer.

Sample Input
3 0 100 1 10 5 100

Sample Output
Case #1: 1 Case #2: 2 Case #3: 13

题意:找出i在0到b之间的f(i)小于等于f(a)的数的个数。

思路:数位dp。主要在于状态转移不好想。dp[i][j]表示i位数比j小的数的个数。用递归完成的话就只需要思考边界和状态转移。

边界:

dp[i][j]如果j小于0,显然是dp[i][j]=0的,如果i==0,说明就是0,显然任何数都比0大,所以dp[i][j]对于j>=0的时候dp[i][j]=1,否则dp[i][j]=0

状态转移:

dp[i][j]+=dp[i-1][j-k*(1<<(i))];j的初始值是sum

完成上述两步推导就能开始写这题了。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MOD = 1000000007;
const int maxn = 200010;
int  num[30],len;
LL  dp[30][10000];
int a[50];
int sum;
LL dfs(int pos,LL zhi,int last)//zhi是差值
{
    if(pos<0) return zhi>=0;//当差值大于等于0时,说明这个数符合要求,+1,否则+0
    if(zhi<0) return 0;//当差值小于0时就+0,
    if(!last&&dp[pos][zhi]!=-1)
    {
        return dp[pos][zhi];
    }
    int len=last?num[pos]:9;
    LL res = 0;
    for(int i=0; i<=len; i++)
    {
        res += dfs(pos-1,(zhi-i*(1<<pos)),last&&(i==len));
    }
    if(!last)dp[pos][zhi]= res;
    return res;
}
LL solve(LL n)
{
    len = 0;
    while(n)
    {
        num[len++] = n%10;
        n /= 10;
    }
    return dfs(len-1,sum,1);//用sum一直去减
}
int main()
{
    memset(dp,-1,sizeof(dp));
    int _;
    scanf("%d",&_);
    int g=0;
    while(_--)
    {
        LL n,m;
        ++g;
        scanf("%I64d%I64d",&m,&n);
        sum=0;
        int l=0;
        while(m)//算sum
        {
            sum+=(m%10)*(1<<l);
            l++;
            m=m/10;
        }
        printf("Case #%d: ",g);
        if(sum==0)
            printf("%d\n",1);
        else
        printf("%I64d\n",solve(n));
    }
    return 0;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP