跳到正文

题解

题解:AT_abc476_g [ABC476G] Increasing Popcount

Chegada_约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年9月22日
收录
2026年10月19日
更新
2026年11月11日
篇幅
约 4 分钟

版本

  1. v1当前

前言

本题解使用折叠框写法,适合希望部分独立思考的读者。建议不要跳过某个提示。

第二次做出 G。

Solution

Hint 1

把 AiA_i 看成给下标 ii 涂的颜色。条件 Ai=Aj⇒popcount⁡(i)<popcount⁡(j)A_i=A_j\Rightarrow \operatorname{popcount}(i)<\operatorname{popcount}(j) 等价于:同一种颜色所染下标的 popcount 两两不同。

于是“最小化最大颜色”就变成了“最少用多少种颜色,能把 [L,R][L,R] 内的下标划分成若干组,每组内下标的 popcount 互异”。

Hint 2

设 ckc_k 为 [L,R][L,R] 中 popcount⁡=k\operatorname{popcount}=k 的下标个数。

每种颜色最多“吃”掉每个 popcount 值一次,所以颜色数不小于 max⁡kck\max_k c_k;反过来把 popcount 相同的一堆下标依次分给编号 1,2,…,ck1,2,\dots,c_k 的颜色,这个下界就能取到。因此

ans=max⁡k≥0ck.\text{ans}=\max_{k\ge 0} c_k.

问题变成:给定 [L,R][L,R],求区间内 popcount 分布的最大值。

Hint 3

L,R≤1018L,R\le 10^{18},逐个数下标肯定不行。像 ABC349_d 那样,把 [L,R][L,R] 按线段树节点自底向上拆:每次从当前左端点 ll 取出尽量长的一段 [l,l+2k)[l,l+2^k),要求 2k∣l2^k\mid l 且不越过 RR。

  • 前者保证 k≤ctz⁡(l)k\le \operatorname{ctz}(l);
  • 后者保证 2k≤R−l+12^k\le R-l+1。

两者取 min⁡\min 就是每次能拆多长。

Hint 4

每一块 [l,l+2k)[l,l+2^k) 里的数写成二进制,是“ll 的高位 ++ 低 kk 位取遍 {0,1}k\{0,1\}^k”,所以其中 popcount⁡=popcount⁡(l)+i\operatorname{popcount}=\operatorname{popcount}(l)+i 的下标恰好有 (ki)\binom{k}{i} 个。

把这块的贡献加到 fs+if_{s+i}(s=popcount⁡(l)s=\operatorname{popcount}(l))上就行。

举个例子:

拆块次数是 O(log⁡(R−L))O(\log(R-L)) 级别的,每块最多贡献 O(log⁡)O(\log) 个二项式系数,单组询问 O(log⁡2R)O(\log^2 R)。

细节
  • 最后 max⁡kfk\max_k f_k 就是答案。原代码里写成后缀 max⁡\max 塞到 f0f_0 输出,效果一样。
  • 多测记得清空 ff。
AC code
C++
using ll = long long;
const int S = 65;
ll c[S][S], f[S];
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    for (int i = 0; i <= 60; ++i) {
        c[i][0] = c[i][i] = 1;
        for (int j = 1; j < i; ++j)
            c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
    }
    int t; cin >> t;
    while (t--) {
        ll l, r; cin >> l >> r;
        fill(f, f + S, 0);
        while (l <= r) {
            int k = __builtin_ctzll(l);
            ll len = r - l + 1;
            while ((1LL << k) > len) --k;
            int s = __builtin_popcountll(l);
            for (int i = 0; i <= k; ++i) f[s + i] += c[k][i];
            l += 1LL << k;
        }
        ll ans = 0;
        for (int i = 0; i <= 60; ++i) ans = max(ans, f[i]);
        cout << ans << '\n';
    }
    return 0;
}
advertisement

如果你也喜欢这种写法,欢迎加入团队。

原文