1. 程式人生 > 實用技巧 >HDU4734 F(x)

HDU4734 F(x)

http://acm.hdu.edu.cn/showproblem.php?pid=4734

演算法:數位DP

dp[pos][V]意味著當第pos位確定時,權值小於V的數有幾個。

稍微計算一下,最高位得權值也不到1000,所以我把V的大小定義為了10000。

#include<bits/stdc++.h>
using namespace std;
int dp[25][10000];//dp[pos][Value]
vector<int>shu;
int getV(int x){
    int ans=0,t=1;
    while(x){
        ans+=x%10*t;
        x
/=10; t*=2; } return ans; } int dfs(int pos,int V,int sp){ if(V<0) return 0; if(pos==-1) return 1; if(!sp&&dp[pos][V]!=-1) return dp[pos][V]; int ans=0; int maxn=sp?shu[pos]:9; for(int i=0;i<=maxn;i++){ ans+=dfs(pos-1,V-i*(1<<pos),sp&&i==maxn); }
if(!sp) dp[pos][V]=ans; return ans; } int cal(int a,int b){ int aV=getV(a); shu.clear(); while(b){ shu.push_back(b%10); b/=10; } return dfs(shu.size()-1,aV,1); } int main(){ memset(dp,-1,sizeof(dp)); int t,a,b;cin>>t; for(int Case=1;Case<=t;Case++){ scanf(
"%d%d",&a,&b); printf("Case #%d: %d\n",Case,cal(a,b)); } }