hdu4734 F(x)(数位dp)

来源:互联网 发布:买家淘宝定制商品 编辑:程序博客网 时间:2024/05/16 17:50

原来把memset清0放在外面可以节省时间!我说怎么老超时。

既然二维数组里的每一项代表位数为pos分别枚举1-9时代表的后面位数的小于给定权值的个数,那就可以一次保存起来不用再算了嘛!


我好笨啊。。。


#include <stdio.h>#include <algorithm>#include <string.h>using namespace std;typedef long long LL;const int N = 21;const int INF = 1e8;LL dp[N][5000], bit[N];LL dfs(int pos, int num, bool limit){    if(pos == 0) return num >= 0;    if(num < 0) return 0;    if(!limit && dp[pos][num] != -1) return dp[pos][num];    int endd = limit ? bit[pos] : 9;    LL ans = 0;    for(int i = 0; i <= endd; i ++)    {        ans += dfs(pos - 1, num - i * (1 << (pos - 1)), limit && (i == endd));    }    if(!limit) dp[pos][num] = ans;    return ans;}LL f(int x){    int ans = 0, tmp = 1;    while(x)    {        ans += ((x % 10) * tmp);        x /= 10;        tmp *= 2;    }    return ans;}LL solve(LL a, LL n){    int len = 0;    while(n)    {        bit[++ len] = n % 10;        n /= 10;    }    return dfs(len, f(a), true);}int main(){ //   freopen("in.txt", "r", stdin);    int t, Case = 1;    LL a, b;    memset(dp, -1, sizeof(dp));    scanf("%d", &t);    while(t --)    {        scanf("%lld%lld", &a, &b);        printf("Case #%d: %lld\n", Case ++, solve(a, b));    }    return 0;}


0 0