思路:dfs搜索
题目要求根据一个子集树搜索最终结果,难点在于剪枝函数。
- 定义dfs参数:w(当前重量), rw(剩余重量)
但是,这样还是不能100AC此题,考虑到当rw+w-a[i] < res时剪枝,所以,当a[i]尽可能大时剪枝更强,故将数组反转(原数组为正序)。
注意:rw可能超过int的范围
代码
int n,C;
int[] a = new int[10000];
int res = 0;
void dfs(int i, int w, long rw) { // 目前看到了第i个
if(i >= n) {
res = Math.max(res, w);
} else {
if(w + a[i] <= C) dfs(i+1, w+a[i], rw-a[i]); //放入
if(rw+w-a[i] > res) dfs(i+1, w, rw-a[i]);
}
}
void test() throws IOException {
Reader cin = new Reader();
n = cin.nextInt();
C = cin.nextInt();
long s = 0;
for(int i = n-1; i >= 0; i--) {
a[i] = cin.nextInt();
s += a[i];
}
dfs(0, 0, s);
System.out.println(res);