先说结论。问题等价于,求满足以下条件的整数 的数量:
- 二进制下,高位第一段连续 1 的长度为偶数;
- ;
- 没了。
简要证明
首先,题目中的式子结合位运算恒等式 ,消去 ,得到 ,这个式子限定了相邻两个二进制位,即
对任意给定的 ,显然可以递推算出 的每一项,构造合法 的方案唯一,所以 只需要对 计数。
另外,设 的最高有效位在第 位,要使 成立,必须 ,然后向下一步步推,就能得到 的二进制表示中最高位连续 的长度为偶数。
至于代码,只需在数位 DP 中维护一个很简单的状态 ,表示
- :在第一段,前缀 1 的个数的奇偶性;
- :已经不在第一段,永远合法。
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 模板)
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;
}