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 <bits/stdc++.h>
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值