Codeforces 1734F 数位 DP

题意

传送门 Codeforces 1734F Zeros and Ones

题解

S i = 1 S_{i} = 1 Si=1 当且仅当 i i i 的二进制表示中 1 1 1 的个数为奇数。问题转化为 [ 0 , m ) [0,m) [0,m) 中,有多少个数字 i i i,满足 i ⊕ ( n + i ) i\oplus (n + i) i(n+i) 在二进制表示下 1 1 1 的个数为奇数。由于加法存在进位的可能,需要枚举不同进位的情况。数位 DP 求解,时间复杂度 O ( log ⁡ max ⁡ ( n , m ) ) O\Big(\log\max(n,m)\Big) O(logmax(n,m))

#include 
using namespace std;
using ll = long long;
constexpr int N = 62;
ll dp[N][2][2][2];

ll rec(int k, int c, int odd, int lim, ll n, ll m) {
    if (k < 0) {
        return c == 0 && odd == 1;
    }
    if (dp[k][c][odd][lim] != -1) {
        return dp[k][c][odd][lim];
    }
    ll res = 0;
    int ub = lim ? (m >> k & 1) : 1;
    for (int i = 0; i <= ub; ++i) {
        for (int d = 0; d < 2; ++d) {
            int x = i + (n >> k & 1) + d;
            if(x / 2 != c) {
                continue;
            }
            res += rec(k - 1, d, odd ^ ((x ^ i) & 1), lim && i == ub, n, m);
        }
    }
    return dp[k][c][odd][lim] = res;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int tt;
    cin >> tt;
    while (tt--) {
        ll n, m;
        cin >> n >> m;
        memset(dp, -1, sizeof(dp));
        m -= 1;
        ll res = rec(N - 1, 0, 0, 1, n, m);
        cout << res << '\n';
    }

    return 0;
}

你可能感兴趣的:(DP,算法)