题解:AT_abc476_g [ABC476G] Increasing Popcount
Chegada_
·
·
题解
前言
本题解使用折叠框写法,适合希望部分独立思考的读者。建议不要跳过某个提示。
第二次做出 G。
Solution
:::info[Hint 1]
把 A_i 看成给下标 i 涂的颜色。条件 A_i=A_j\Rightarrow \operatorname{popcount}(i)<\operatorname{popcount}(j) 等价于:同一种颜色所染下标的 popcount 两两不同。
| 于是“最小化最大颜色”就变成了“最少用多少种颜色,能把 [L,R] 内的下标划分成若干组,每组内下标的 popcount 互异”。 |
:::info[Hint 2]
设 c_k 为 [L,R] 中 \operatorname{popcount}=k 的下标个数。
每种颜色最多“吃”掉每个 popcount 值一次,所以颜色数不小于 \max_k c_k;反过来把 popcount 相同的一堆下标依次分给编号 1,2,\dots,c_k 的颜色,这个下界就能取到。因此
\text{ans}=\max_{k\ge 0} c_k.
| 问题变成:给定 [L,R],求区间内 popcount 分布的最大值。 |
:::info[Hint 3]
- 前者保证 $k\le \operatorname{ctz}(l)$;
- 后者保证 $2^k\le R-l+1$。
两者取 $\min$ 就是每次能拆多长。
:::
:::info[Hint 4]
每一块 $[l,l+2^k)$ 里的数写成二进制,是“$l$ 的高位 $+$ 低 $k$ 位取遍 $\{0,1\}^k$”,所以其中 $\operatorname{popcount}=\operatorname{popcount}(l)+i$ 的下标恰好有 $\binom{k}{i}$ 个。
把这块的贡献加到 $f_{s+i}$($s=\operatorname{popcount}(l)$)上就行。
举个例子:

拆块次数是 $O(\log(R-L))$ 级别的,每块最多贡献 $O(\log)$ 个二项式系数,单组询问 $O(\log^2 R)$。
:::
:::info[细节]
- 最后 $\max_k f_k$ 就是答案。原代码里写成后缀 $\max$ 塞到 $f_0$ 输出,效果一样。
- 多测记得清空 $f$。
:::
:::success[AC code]
```cpp
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;
}
```
:::
:::info[advertisement]
如果你也喜欢这种写法,欢迎加入[团队](https://www.luogu.com.cn/team/126621)。
:::