题解:CF2252E Generational Triplets

· · 题解

先说结论。问题等价于,求满足以下条件的整数 c 的数量:

::::info[简要证明] 首先,题目中的式子结合位运算恒等式 a + c = (a \oplus c) + 2(a \land c),消去 b,得到 a \oplus c = 2(a \land c),这个式子限定了相邻两个二进制位,即

a_i \oplus c_i = a_{i-1} \land c_{i-1}

对任意给定的 c,显然可以递推算出 a 的每一项,构造合法 a 的方案唯一,所以 只需要对 c 计数。

另外,设 c 的最高有效位在第 k 位,要使 a < c 成立,必须 a_k = 0,然后向下一步步推,就能得到 c 的二进制表示中最高位连续 1 的长度为偶数。

至于代码,只需在数位 DP 中维护一个很简单的状态 s,表示

struct State {
    unsigned s = 0;

    State next(unsigned d, bool less, bool plus) const {
        if (s == 404) return {404}; // 不合法状态
        if (s == 2) return {2};     // 永远合法状态

        if (!plus) { // 有前导零,进入第一段
            return {d};
        } else {
            if (d == 0) { // 第一段结束,判断合法性
                if (s == 0) return {2};
                if (s == 1) return {404};
            } else {
                return {s ^ 1};
            }
        }
    }
};

完整代码如下(顺便分享我的新数位 DP 模板)

::::info[Code]

#include <bits/stdc++.h>
using namespace std;

constexpr unsigned mod = 1000000007;

void add(unsigned& a, unsigned b) {
    a += b;
    if (a >= mod) a -= mod;
}

struct State {
    unsigned s = 0;
    // 404: 不合法状态
    // 2: 永远合法状态
    // 0/1: 1 的个数的奇偶性

    auto operator<=>(const State&) const = default;

    bool is_valid() const {
        return s == 0 || s == 2;
    }

    State next(unsigned d, bool less, bool plus) const {
        if (s == 404) return {404}; // 不合法状态
        if (s == 2) return {2};     // 永远合法状态

        if (!plus) { // 有前导零,进入第一段
            return {d};
        } else {
            if (d == 0) { // 第一段结束,判断合法性
                if (s == 0) return {2};
                if (s == 1) return {404};
            } else {
                return {s ^ 1};
            }
        }
    }
};

// 以下都是数位 DP 的模板

using u64 = unsigned long long;

int main() {
    cin.tie(nullptr)->sync_with_stdio(false);

    int T {1};
    cin >> T;

    while (T--) {
        u64 N;
        cin >> N;

        auto calc = [&](u64 val) {
            vector<map<State, unsigned>> memo(64);

            return [&](this auto&& self, unsigned i, bool less, bool plus, State s) -> unsigned {
                if (i == -1) return s.is_valid();

                if (less && plus && memo[i].contains(s)) {
                    return memo[i][s];
                }

                unsigned D = val >> i & 1;

                unsigned res = 0;

                for (unsigned d = 0; d <= (less ? 1 : D); d++) {
                    auto new_less = less | (d < D);
                    auto new_plus = plus | (d > 0);
                    auto new_state = s.next(d, less, plus);

                    add(res, self(i - 1, new_less, new_plus, new_state));
                }

                if (less && plus) {
                    memo[i][s] = res;
                }

                return res;
            } (63, {}, {}, {});
        };

        cout << calc(N) - 1 << "\n";
    }

    return 0;
}

::::