题解:CF2252E Generational Triplets

· · 题解

给定 n,求满足下列条件的 (a,b,c) 的数目:

对 10^9+7 取模。

多测,\sum n \le 10^{18},2 秒,250 MB。

对条件进行简单转化可得 2(a \oplus c) = a+c,考虑对无序对 (a,c) 计数,减掉 (0,0) 后除以二即为答案。

从高位向低位进行数位 DP,枚举某个当前位上 a, c 分别填什么、低位传来的进位进行转移。为了检查条件是否满足,需要记录 a+c 的进位,这一位 a \oplus c 的限制,以及 a,c 是否受 \le n 的限制,对着题意写记搜即可,复杂度是 1log 的。

#define int long long
int n, a[65];
mint f[65][2][2];
mint dfs(int d, int c, int v, bool lim1, bool lim2) {
    if (d == -1) return c == 0 && v == 0;
    if (!lim1 && !lim2 && f[d][c][v].val != (u32)-1) return f[d][c][v];
    mint res = 0;
    for (int x : {0, 1}) for (int y : {0, 1}) {
        if (lim1 && x > a[d]) continue;
        if (lim2 && y > a[d]) continue;
        if ((x ^ y) != v) continue;
        for (int z : {0, 1}) {
            int q = x + y + z;
            if (q / 2 != c) continue;
            res += dfs(d - 1, z, q & 1, lim1 && (x == a[d]), lim2 && (y == a[d]));
        }
    }
    if (!lim1 && !lim2) f[d][c][v] = res;
    return res;
}

void _main() {
    cin >> n;
    for (int i = 0; i <= 61; i++) a[i] = n >> i & 1;
    cout << (dfs(61, 0, 0, 1, 1) - 1) / 2 << '\n';
}