跳到正文

个人记录

CH2401 送礼物[双向搜索]

Colin_Lovecraft约 2 分钟
原文
文章信息与版本

文章信息

发布
2019年9月20日
收录
2026年8月31日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前

直接暴力枚举复杂度过高,可以折半进行搜索。

具体来说,先搜索前一半可以组合出的不超过WW的重量,再搜索后一半可以组合出的不超过WW的重量wiw_i再用二分查找,在第一次搜索得出的重量中找到不超过W−wiW - w_i的最大重量,与wiw_i一起更新答案。

按重量降序排序会减少分支,第二次搜索还需要二分查找,可适当调小后半段的大小。

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

const int N = 50;
int w, n, a[N], ans;
vector<int> v;

void dfs1(int i, int now) {
	if(!i) {
		v.push_back(now);
		return ;
	}
	dfs1(i - 1, now);
	if(1ll * now + a[i] <= w) dfs1(i - 1, now + a[i]); 
}

void dfs2(int i, int now) {
	if(i == n + 1) {
		int x = *(upper_bound(v.begin(), v.end(), w - now) - 1);
		ans = max(ans, x + now);
		return ;
	}		
	dfs2(i + 1, now);
	if(1ll * now + a[i] <= w) dfs2(i + 1, now + a[i]);
}

int main() {
	cin >> w >> n;
	for(int i = 1; i <= n; i++) cin >> a[i];
	sort(a + 1, a + n + 1);
	reverse(a + 1, a + n + 1);
	int d = n / 2 + 2;
	dfs1(d, 0);
	sort(v.begin(), v.end());
	unique(v.begin(), v.end());
	dfs2(d + 1, 0);
	cout << ans << endl;
	return 0;
}
原文