zoukankan      html  css  js  c++  java
  • Balanced Number (思维数位dp)

    A balanced number is a non-negative integer that can be balanced if a pivot is placed at some digit. More specifically, imagine each digit as a box with weight indicated by the digit. When a pivot is placed at some digit of the number, the distance from a digit to the pivot is the offset between it and the pivot. Then the torques of left part and right part can be calculated. It is balanced if they are the same. A balanced number must be balanced with the pivot at some of its digits. For example, 4139 is a balanced number with pivot fixed at 3. The torqueses are 4*2 + 1*1 = 9 and 9*1 = 9, for left part and right part, respectively. It's your job 
    to calculate the number of balanced numbers in a given range [x, y].

    Input

    The input contains multiple test cases. The first line is the total number of cases T (0 < T ≤ 30). For each case, there are two integers separated by a space in a line, x and y. (0 ≤ x ≤ y ≤ 10 18).

    Output

    For each case, print the number of balanced numbers in the range [x, y] in a line.

    Sample Input

    2
    0 9
    7604 24324

    Sample Output

    10
    897

    数位dp难在dp数组所储存的状态

    此题枚举配合dp枚举平衡杠杆的位置

    dp数组三维分别代表数位 位置 当前加和

    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    #include<iostream>
    using namespace std;
    long long dp[20][20][2000];
    int a[20];
    long long dfs(int lim,int pos,int k,int sum,int now)
    {
        if(pos==0) return sum==0;
        long long ans=0;
        if(!lim&&dp[pos][k][sum]!=-1) return dp[pos][k][sum];
        int s=lim?a[pos]:9;
        for(int i=0;i<=s;i++)
        {
            ans+=dfs(lim&&i==s,pos-1,k,sum+now*i,now-1);
        }
        if(!lim) dp[pos][k][sum]=ans;
        return ans;
    }
    long long solve(long long x)
    {
        if(x==-1) return 0;
        int cnt=0;
        while(x!=0)
        {
            cnt++;
            a[cnt]=x%10;
            x/=10;
        }
        long long ans=1;
        for(int i=1;i<=cnt;i++)
        {
            ans+=dfs(1,cnt,i,0,cnt-i)-1;
        }
        return ans;
    }
    int main()
    {
        memset(dp,-1,sizeof(dp));
        int t;
        scanf("%d",&t);
        while(t--)
        {
            long long temp1,temp2;
            scanf("%lld%lld",&temp1,&temp2);
            cout<<solve(temp2)-solve(temp1-1)<<endl;
        }
    }
  • 相关阅读:
    docker生态系统
    访问远程的docker
    docker实践4
    docker实践3
    docker实践
    Spark快速入门
    shuffle和sort分析
    hadoop原理
    apacheds的客户端
    LDAP apacheds解决方案
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852311.html
Copyright © 2011-2022 走看看