zoukankan      html  css  js  c++  java
  • hdu3709 Balanced Number[数位dp]

    Balanced Number

    Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
    Total Submission(s): 5376    Accepted Submission(s): 2571


    Problem Description
    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 ≤ 1018).
     
    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
     
    Author
    GAO, Yuan
     
    Source

    #include<cstdio>
    #include<cstring>
    #include<iostream>
    using namespace std;
    typedef long long ll;
    const int N=20;
    ll l,r,f[N][N][N*101];int T,bits[N];
    ll dfs(int pos,int x,int st,bool lim){
        if(!pos) return !st;
        if(st<0) return 0;
        ll &res=f[pos][x][st],ans=0;
        if(!lim&&(~res)) return res;
        int up=!lim?9:bits[pos];
        for(int i=0;i<=up;i++){
            ans+=dfs(pos-1,x,st+i*(pos-x),lim&&i==bits[pos]);
        }
        if(!lim) res=ans;
        return ans;
    }
    ll solve(ll x){
        if(x<0) return 0;
        int len=0;ll ans=0;
        for(;x;x/=10) bits[++len]=x%10;
        for(int i=1;i<=len;i++) ans+=dfs(len,i,0,1);
        return ans-len+1;
    }
    int main(){
        memset(f,-1,sizeof f);
        for(scanf("%d",&T);T--;)
            scanf("%I64d%I64d",&l,&r),
            printf("%I64d
    ",solve(r)-solve(l-1));
        return 0;
    }
  • 相关阅读:
    98. 验证二叉搜索树
    236. 二叉树的最近公共祖先
    leetcode 字符串转换整数 (atoi)
    LeetCode 寻找两个正序数组的中位数 (找第k个数的变种)
    Leetcode 面试题 16.18. 模式匹配(逻辑题)(转)
    深入学习Redis(4):哨兵(转)
    【BAT面试题系列】面试官:你了解乐观锁和悲观锁吗?(转)
    CentOS 7.5 使用 yum 方式安装 MySQL 5.7
    CentOS7 安装 PHP7 完全详细教程
    ubunutu 18.04 编译php7.4.1
  • 原文地址:https://www.cnblogs.com/shenben/p/6708758.html
Copyright © 2011-2022 走看看