PrevNext

折半搜索

重点例题 – 继续学习之前,请先尽力独立解决这道题!

教程

实用技巧

折半搜索可以利用较小的数据范围,把朴素解法分成两半分别计算。 因此,与直接搜索相比,它通常能处理约两倍规模的数据。

朴素解法

遍历数组的所有子集;如果某个子集的元素和等于 xx,就将答案加一。 最坏情况下,这需要进行约 2402^{40} 次操作,远远太慢。

折半搜索解法

可以把给定数组分成两个独立的数组。设 left\texttt{left} 数组包含下标 00 到 n2−1\frac{n}{2}-1 的元素,right\texttt{right} 数组包含下标 n2\frac{n}{2} 到 n−1n-1 的元素。 两个数组都至多包含 2020 个元素,因此最多只需 2212^{21} 次操作就能遍历它们的所有子集,完全可以接受。

得到两个数组各自的所有子集和后,需要重新组合它们来寻找答案。对于 left\texttt{left} 中的每个 sum\texttt{sum},只需检查 right\texttt{right} 中有多少个值等于 x−sumx-\texttt{sum}。这可以用简单的二分查找完成。

时间复杂度:O(N⋅2N/2)O(N\cdot 2^{N/2})

Warning!

下面的解法只有使用 PyPy 提交时才能在时限内运行完毕。

import collections
n, x = map(int, input().split())
t = list(map(int, input().split()))
def get_subset_sums(l: int, r: int) -> collections.Counter:
sums = [0]
for ti in t[l:r]:
sums.extend([s + ti for s in sums])

题目

StatusSourceProblem NameDifficultyTags
CFEasy
Show TagsBinary Search, Meet in the Middle
SilverEasy
Show TagsMeet in the Middle, Two Pointers
CFEasy
Show TagsBinary Search, DFS, Meet in the Middle
YSMedium
Show TagsBitmasks, DP, Meet in the Middle
CFHard
Show TagsDFS, Meet in the Middle, Number Theory
CFHard
Show TagsBinary Search, DFS, Meet in the Middle
KattisHard
Show TagsDFS, Meet in the Middle, PIE

Module Progress:

PrevNext