题解:CF2252E Generational Triplets
先说结论。问题等价于,求满足以下条件的整数
- 二进制下,高位第一段连续 1 的长度为偶数;
-
- 没了。
::::info[简要证明]
首先,题目中的式子结合位运算恒等式
对任意给定的
| 另外,设 |
|---|
至于代码,只需在数位 DP 中维护一个很简单的状态
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;
}
::::