HDU - 4734 数位dp

来源:互联网 发布:php处理ajax post请求 编辑:程序博客网 时间:2024/06/05 08:46

题意:

定义F(x),若数x的十进制表示可以写成(A nA n-1A n-2 ... A 2A 1),那么F(x)定义为F(x) = An * 2^(n-1) + An-1 * 2^(n-2) + ... + A2 * 2 + A1 * 1,先给出A,B,求出0到B之间F(x)小于等于F(A)的数有多少个?

思路:

数位dp,可以发现最大的A也就是999999999,F(A)的最大值不超过5000,那么可以设计dp[pos][bit_sum]表示数位小于等于pos且F(x)小于等于bit_sum的数有多少个,套用模板即可求解。

代码:

#include <bits/stdc++.h>using namespace std;typedef long long ll;ll two[20], dp[20][5000];int a[20];void init() {    two[0] = 1;    for (int i = 1; i <= 10; i++)        two[i] = two[i - 1] * 2;    memset(dp, -1, sizeof(dp));}ll dfs(int pos, int bit_sum, bool limit) {    if (pos == -1){        if (bit_sum >= 0) return 1;        return 0;    }    if (!limit && dp[pos][bit_sum] != -1) return dp[pos][bit_sum];    int up = limit ? a[pos] : 9;    ll res = 0;    for (int i = 0; i <= up; i++) {        if (bit_sum - i * two[pos] < 0) break;        res += dfs(pos - 1, bit_sum - i * two[pos], limit && a[pos] == i);    }    if (!limit) dp[pos][bit_sum] = res;    return res;}ll solve(ll x, ll y) {    int pos = 0;    while (x) {        a[pos++] = x % 10;        x /= 10;    }    int bit_sum = 0, cnt = 0;    while (y) {        bit_sum += (y % 10) * two[cnt++];        y /= 10;    }    return dfs(pos - 1, bit_sum, true);}int main() {    init();    int T, cs = 0;    scanf("%d", &T);    while (T--) {        int x, y;        scanf("%d%d", &x, &y);        printf("Case #%d: %I64d\n", ++cs, solve(y, x));    }    return 0;}


0 0
原创粉丝点击