首页 > ACM题库 > HDU-杭电 > HDU 3709-Balanced Number-动态规划-[解题报告]HOJ
2015
02-21

HDU 3709-Balanced Number-动态规划-[解题报告]HOJ

Balanced Number

问题描述 :

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].

输入:

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).

输出:

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).

样例输入:

2
0 9
7604 24324

样例输出:

10
897

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3709

题目大意就是求给定区间内的平衡数的个数

要明白一点:对于一个给定的数,假设其位数为n,那么可以有n个不同的位作为支点,但每次只能有一个支点

定义dp[len][pos][k],len表示当前还需处理的位数,pos表示当前的所选的支点的位置,k表示计算到当前的力矩之和(即从最高位到第len+1位)

容易知道如果在某一个len>1的位置k已经小于0,那么就可以直接剪枝

代码如下 :

 #include<iostream>
 #include<cstdlib>
 #include<cstring>
 #include<cstdio>
 using namespace std;
 int bit[20];
 long long int dp[20][20][2000];
 long long  int x,y;
 
 
 long long int dfs(int len,int pos,int sum,bool flag )
 {
     long long int ans=0;
    if(len==0 ) return sum==0;
    if(sum<0) return 0;
    if(flag && dp[len][pos][sum]>=0) return dp[len][pos][sum];
 
    int tmp=flag?9:bit[len];
 
    for(int i=0;i<=tmp;i++)
    {
        int n_sum=sum;
        n_sum+=i*(len-pos);
        ans+=dfs(len-1,pos,n_sum,flag||i<tmp);
    }
    if(flag) dp[len][pos][sum]=ans;
    return ans;
 }
 long long int solve(long long int n)
 {
    int len=0;
    while(n) bit[++len]=n%10,n/=10;
    long long int ans=0;
    for(int i=1;i<=len;i++)
    {
       ans+=dfs(len,i,0,0);
    }
 
   return ans-(len-1);
    
 }
 int main()
 {
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%64d %64d",&x,&y);
        memset(dp,-1,sizeof(dp));
        cout<<solve(y)<<endl;
     
    }
    return 0;
 }

 

 

参考:http://www.cnblogs.com/xiaozhuyang/archive/2013/09/19/hdu3709.html


  1. 问题3是不是应该为1/4 .因为截取的三段,无论是否能组成三角形, x, y-x ,1-y,都应大于0,所以 x<y,基础应该是一个大三角形。小三角是大三角的 1/4.

  2. 很高兴你会喜欢这个网站。目前还没有一个开发团队,网站是我一个人在维护,都是用的开源系统,也没有太多需要开发的部分,主要是内容整理。非常感谢你的关注。