hdu3709 Balanced Number (數位dp)
阿新 • • 發佈:2018-10-09
careful href multi true search target tar sta total
to calculate the number of balanced numbers in a given range [x, y].
Sample Input
2
0 9
7604 24324
比如4139 以3為支點,則4*2+1+1==9*1
題解:數位dp,dp[i][j][k]:i表示數位,j表示支點,k表示力矩和
代碼:
題目傳送門
Balanced Number
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 7994 Accepted Submission(s): 3816
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 Output 10 897
Author GAO, Yuan
Source 2010 Asia Chengdu Regional Contest
Recommend zhengfeng | We have carefully selected several similar problems for you: 3711 3715 3718 3713 3712 題意:求平衡數,就是以一個數位為支點,左右兩邊的力矩相等
代碼:
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
typedef long long ll;
ll n,m;
ll dp[20][20][2000];//多加一維表示力矩
int bit[20];
ll dfs(int pos,int center,int sum,bool limit)
{
if(pos==-1) return sum==0;
if(sum<0)return 0;//剪枝
if(!limit&&dp[pos][center][sum]!=-1) return dp[pos][center][sum];
int up=limit?bit[pos]:9;
ll ans=0;
for(int i=0;i<=up;i++)
ans+=dfs(pos-1,center,sum+(pos-center)*i,limit&&i==up);
if(!limit) dp[pos][center][sum]=ans;
return ans;
}
ll calc(ll n)
{
int len=0;
while(n)
{
bit[len++]=n%10;
n/=10;
}
ll ans=0;
for(int i=len-1;i>=0;i--)
ans+=dfs(len-1,i,0,true);
return ans-(len-1);//排除0、00、000....的幹擾
}
int main()
{
int T;
scanf("%d",&T);
memset(dp,-1,sizeof(dp));
while(T--)
{
scanf("%lld %lld",&n,&m);
printf("%lld\n",calc(m)-calc(n-1));
}
return 0;
}
hdu3709 Balanced Number (數位dp)