12人阅读 评论(0)

# Balanced Number

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

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

2
0 9
7604 24324

10
897

## 代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define ll long long
using namespace std;
int n;
ll dp[20][20][10000];
int a[30];
int pos;
ll dfs(int pos,int balance,int sum,int limit)
{
if(pos==-1)
return sum==0;
if(sum<0)
return 0;
if(dp[pos][balance][sum]!=-1&&(!limit))
return dp[pos][balance][sum];
int up= limit ? a[pos] : 9;
ll Tmp=0;
for(int i=0;i<=up;i++)
Tmp+=dfs(pos-1,balance,sum+(pos-balance)*i,limit && i==up);
if(!limit)
dp[pos][balance][sum]=Tmp;
return Tmp;
}
ll solve(ll x)
{
pos=0;
while(x)
{
a[pos++]=x%10;
x/=10;
}
ll sum=0;
for(int i=pos-1;i>=0;i--)
sum+=dfs(pos-1,i,0,true);
return sum-pos;
}
int main()
{
memset(dp,-1,sizeof(dp));
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
ll x,y;
scanf("%I64d%I64d",&x,&y);
printf("%I64d\n",solve(y)-solve(x-1));
}
return 0;
}

个人资料
等级：
访问量： 1934
积分： 792
排名： 6万+
友链