HDU 4734 F(x) 数位dp
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=4734
F(x)
Memory Limit: 32768/32768 K (Java/Others)
题解
数位dp,这题求的是<=的所有情况,这和求==的唯一差别就是初始化:
return k>=0;
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<ctime>
#include<vector>
#include<cstdio>
#include<string>
#include<bitset>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
#define X first
#define Y second
#define mkp make_pair
#define lson (o<<1)
#define rson ((o<<1)|1)
#define mid (l+(r-l)/2)
#define sz() size()
#define pb(v) push_back(v)
#define all(o) (o).begin(),(o).end()
#define clr(a,v) memset(a,v,sizeof(a))
#define bug(a) cout<<#a<<" = "<<a<<endl
#define rep(i,a,b) for(int i=a;i<(b);i++)
#define scf scanf
#define prf printf
typedef int LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef vector<pair<int,int> > VPII;
const int INF=0x3f3f3f3f;
const LL INFL=0x3f3f3f3f3f3f3f3fLL;
const double eps=1e-8;
const double PI = acos(-1.0);
//start----------------------------------------------------------------------
const int maxn=11;
const int maxm=4666;
int arr[maxn],tot;
int dp[maxn][maxm];
int bin[maxn];
///ismax标记表示前驱是否是边界值
LL dfs(int len,int k, bool ismax) {
if(k<0) return 0;
if (len == 0) {
///递归边界,求"恰好等于"和"小于等于"唯一的区别是:
///return k==0 VS return k>=0
return k>=0;
}
if (!ismax&&dp[len][k]>=0) return dp[len][k];
LL res = 0;
int ed = ismax ? arr[len] : 9;
///这里插入递推公式
for (int i = 0; i <= ed; i++) {
res += dfs(len - 1, k-i*bin[len-1], ismax&&i == ed);
}
return ismax ? res : dp[len][k] = res;
}
LL solve(LL x,int y) {
tot = 0;
int k=0,tmp=1;
while (x) {
k+=(x % 10)*tmp; x /= 10;
tmp*=2;
}
while (y) { arr[++tot] = y % 10; y /= 10; }
return dfs(tot, k, true);
}
int main() {
bin[0]=1;
for(int i=1;i<maxn;i++) bin[i]=bin[i-1]*2;
clr(dp,-1);
int tc,kase=0;
scf("%d",&tc);
while(tc--){
int x,y;
scf("%d%d",&x,&y);
prf("Case #%d: %d\n",++kase,solve(x,y));
}
return 0;
}
//end-----------------------------------------------------------------------
Notes
一直在想求<=要怎么办,枚举(0,1,2,3,。。。,k)? 复杂度有点高。。。。。
其实,把状态dp[len][k]定义成前len位所有<=k的情况,然后只要改下初始化就行了xrz