当前位置: 代码迷 >> 综合 >> HDU- 3709 Balanced Number(数位dp)
  详细解决方案

HDU- 3709 Balanced Number(数位dp)

热度:48   发布时间:2023-11-17 11:02:57.0
题目地址:点此传送
题目
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
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
题意

很简单,就是求[a,b]之间满足条件的数有多少个,条件举个例子来说(平衡数),例如4139 这个当中心是3时左边为1*1+4*2=9右边为1*9,左边等于右边这算是一个平衡数,问你有多少这样的平衡数

思路

数位dp,dp[len][pos][sum] len代表第几位数字,pos代表以pos为中心,sum代表平衡数两边的的差,这道题可以遍历中心pos来进行数位dp,当len<0且sum=0时代表是一个平衡数,sum可以用一种方法表示,到pos的距离乘以的d[i](第i位)

代码
#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
#define ll long long
#define rd(a) scanf("%d",&a)
#define rld(a) scanf("%lld",&a)
#define rs(a) scanf("%s",a)
#define me(a,b) memset(a,b,sizeof(a))
#define pb(a) push_back(a)
const ll maxn=3e5+10;
const ll mod =1e9+7;
const ll inf =0x3f3f3f3f;
const double PI=acos(-1);
int d[20];
ll dp[20][20][2000];
ll dfs(int len,int pos,int limit,int sum){if(len<0) return sum==0;if(sum<0) return 0;if(!limit&&dp[len][pos][sum]!=-1) return dp[len][pos][sum];int end=limit?d[len]:9;ll ans=0;for(int i=0;i<=end;i++){ans+=dfs(len-1,pos,limit&(i==end),sum+i*(len-pos));}if(!limit) dp[len][pos][sum]=ans;return ans; }
ll solve(ll x){int len=0;while(x){d[len++]=x%10;x/=10;}ll ans=0;for(int i=0;i<len;i++)ans+=dfs(len-1,i,1,0);return ans-len+1;
}int main(){me(dp,-1);int t;rd(t);while(t--){ll a,b;rld(a),rld(b);printf("%lld\n",solve(b)-solve(a-1));}return 0;
}
  相关解决方案