折半搜索
重点例题 – 继续学习之前,请先尽力独立解决这道题!
教程
| Resources | |||||
|---|---|---|---|---|---|
| CPH | |||||
| Errichto | |||||
实用技巧
折半搜索可以利用较小的数据范围,把朴素解法分成两半分别计算。 因此,与直接搜索相比,它通常能处理约两倍规模的数据。
朴素解法
遍历数组的所有子集;如果某个子集的元素和等于 ,就将答案加一。 最坏情况下,这需要进行约 次操作,远远太慢。
折半搜索解法
可以把给定数组分成两个独立的数组。设 数组包含下标 到 的元素, 数组包含下标 到 的元素。 两个数组都至多包含 个元素,因此最多只需 次操作就能遍历它们的所有子集,完全可以接受。
得到两个数组各自的所有子集和后,需要重新组合它们来寻找答案。对于 中的每个 ,只需检查 中有多少个值等于 。这可以用简单的二分查找完成。
时间复杂度:
Warning!
下面的解法只有使用 PyPy 提交时才能在时限内运行完毕。
import collectionsn, 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])
题目
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| CF | Easy | Show TagsBinary Search, Meet in the Middle | ||||
| Silver | Easy | Show TagsMeet in the Middle, Two Pointers | ||||
| CF | Easy | Show TagsBinary Search, DFS, Meet in the Middle | ||||
| YS | Medium | Show TagsBitmasks, DP, Meet in the Middle | ||||
| CF | Hard | Show TagsDFS, Meet in the Middle, Number Theory | ||||
| CF | Hard | Show TagsBinary Search, DFS, Meet in the Middle | ||||
| Kattis | Hard | Show TagsDFS, Meet in the Middle, PIE | ||||