zoukankan      html  css  js  c++  java
  • 【HDU3709】平衡数Balanced Number

    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 42 + 11 = 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


    思路

    • 首先,对于某个非0的数,最多可能有一个pivot的位置。
    • 由于0对于每个位置都会被统计到,最后要再减去重复个数
    • dp[i][j][k],i是长度,j是支点,k是力矩和,dp[i][j][k]是以j为支点的平衡数的数量
    • sum在支点一侧增加,另一侧减小,最后和为0满足题目条件

    代码

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #define int long long
    using namespace std;
    int bit[20],dp[20][20][2005];
    int dfs(int x,int point,int sum,int flag)
    {
    	if(x==1) return sum==0;
    	if(sum<0) return 0;//小于0时一定不是支点,返回0
    	if(!flag&&dp[x][point][sum]!=-1) return dp[x][point][sum];
    	int count=flag?bit[x-1]:9,ans=0;
    	for(int i=0;i<=count;++i) ans+=dfs(x-1,point,sum+(x-1-point)*i,flag&&i==count);
    	return flag?ans:dp[x][point][sum]=ans;
    }
    long long start(long long x)
    {
    	int len=0; long long ans=0; memset(dp,-1,sizeof(dp));
    	for(;x;x/=10) bit[++len]=x%10;
    	for(int i=1;i<=len;++i) ans+=dfs(len+1,i,0,1);
    	return ans-(len-1);
    }
    signed main()
    {
    	int n; scanf("%lld",&n);
    	while(n--)
    	{
    		long long a,b; scanf("%lld%lld",&a,&b);
    		printf("%lld
    ",start(b)-start(a-1));
    	}
    	return 0;
    }
    
  • 相关阅读:
    [转]oracle数据库定时任务dbms_job的用法详解
    身份证号码的正则表达式及验证详解(JavaScript,Regex)
    js数组操作
    jq滚动到底部加载更多方法
    jq之实现轮播
    node之npm一直出错
    Jq之21点游戏
    移动端屏幕适配viewport
    meta属性
    用户体验之表单结构
  • 原文地址:https://www.cnblogs.com/wuwendongxi/p/13307487.html
Copyright © 2011-2022 走看看