分享一个非常智慧的做法,从 tutorial 评论区看到的
发现答案长度越大,留给这堆线段施展的空间就越大,也就是答案更容易合法。于是考虑二分答案 。
如何 check?
当时想了半天如何贪心,总是想不出正确的策略,遂放弃。
但是贪心 check 的本质还是逐条插入线段,验证每条线段的结尾端点能否落到这个长度为 的区间里。
于是我们考虑直接维护这个东西!!
设 数组 表示考虑前 条线段,第 个位置能()否()成为第 条线段结尾位置;换句话说,第 个位置能否成为第 条线段开始位置。
Tips:
b[j][i]表示第 i 位能否成为第 j + 1 条线段的起始点。注意这里实际上并没有考虑第 j + 1 条线段的能否“成功地”放在这里(因为定义 1 只“考虑了前 j 条线段”能否“成功”放下),只是考虑了第 i 位“有没有可能”成为它的起始点,所以第 1 条线段是“可能”可以放在任何起始点的。接下来转移的时候,才开始考虑这条将要放下的线段的长度,也就是能否“成功地”放在这里。
考虑新加入一条线段长度为 ,对所有(答案不会越界的)位置 ,它能成为结尾当且仅当位置 至少有一个能成为开头,也就是:
当前的答案满足条件意味着 至少有一个位置为 。
快速维护这个 数组可以通过 std::bitset 实现。可以直接滚动数组把第一维优化掉。
代码实现
注释写的英文是因为我同时在用 Dev-C++ 和 VSCode,为了防止编码混乱才写成英文的。
关于那个神奇的式子可以参考下图(线是 1,实心块是 0):
const int MAXN = 10000 + 10;
int n, aa[MAXN];
std::bitset<MAXN> s, t;
// (after j loops) s[i] means (after considering the first j segs)
// whether the jth seg's end can be placed on pos i
// in other words, (before the (j + 1)th loop) s[i] means (after considering the first j segs)
// whether it's possible to place the (j + 1)th seg's start on pos i
// jth seg's end can be placed on pos i if and only if its start can be placed on pos (i - len) or (i + len)
// that is, forall i, new_s[i] = s[i - len] | s[i + len]
bool check(int mid) {
s = 0; t = 0;
for (int i = 0; i <= std::min(mid, MAXN - 1); ++i) t.set(i);
s = t;
for (int i = 1; i <= n; ++i) {
s = ((s >> aa[i]) | (s << aa[i])) & t;
// this magic thing equals to:
// for (int j = 1; j <= n; ++j) {
// new_s[j] = s[j - aa[i]] | s[j + aa[i]];
// }
} return s.count();
}
int main() {
std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int T; cin >> T;
while (T --> 0) {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> aa[i];
int l = 1, r = 2e7, ans = 0;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid)) r = mid - 1, ans = mid;
else l = mid + 1;
} cout << ans << endl;
}
return 0;
}