[hdu 4734]F(x)

For a decimal number x with n digits (AnAn-1An-2 … A2A1), we defineits weight as F(x) = An * 2n-1 + An-1 * 2n-2 + … + A2 * 2 + A1 * 1.
Now you are given two numbers A and B, please calculate how many numbers are there between 0 and B, inclusive, whose weight is no more than F(A).引用地有点丑。

这道题在看翻译后马上知道是数位dp,不过呢,这题运用到了一些新思维。如果定义f[i][j] (j为i位数的和)为j<=F[A]的个数的话,这个状态就会跟F(A)有关,memset需要放在for里面,那么我们为了把memset给变到for外面的话,就需要多开一维,表示F(A),以此来分别记录,但这会爆空间。
所以我们重新定义f[i][j],j一开始为F(A),在之后的搜索中减去值,到最后,如果j>=0,就统计答案,表面上看这好像没有区别,实际上这样记录状态就不跟F(A)有关了,所以我们就可以理直气壮地把memset放在for外面了。

#include
#include
#include
#include
#include
using namespace std;
int wy[11],a[11];
long long f[11][50000];
long long dfs(int pos,int sta,bool limt)
{
    if(sta>=0 && pos==0)return 1;
    if(sta<0)return 0;
    if(limt==false && f[pos][sta]!=-1)return f[pos][sta];
    int up=9,ans=0;
    if(limt==true)up=a[pos];
    for(int i=0;i<=up;i++)
    {
        bool bk=false;
        if(limt==true && i==a[pos])bk=true;
        ans+=dfs(pos-1,sta-i*wy[pos-1],bk);
    }
    if(limt==false)f[pos][sta]=ans;
    return ans;
}   
long long solve(int x)
{
    int pos=0;
    while(x!=0)
    {
        a[++pos]=x%10;
        x/=10;
    }
    return pos;
}
int main()
{
    int T;
    scanf("%d",&T);
    wy[0]=1;
    for(int i=1;i<=9;i++)wy[i]=wy[i-1]*2;
    memset(f,-1,sizeof(f));
    for(int t=1;t<=T;t++)
    {
        int n,m,s=0,pos,ans;
        scanf("%d%d",&n,&m);
        pos=solve(n);for(int i=1;i<=pos;i++)s+=a[i]*wy[i-1];
        pos=solve(m);ans=dfs(pos,s,true);
        printf("Case #%d: %d\n",t,ans);
    }
    return 0;
}

你可能感兴趣的:(hdu,数位dp)