AcWing 165. 【java】小猫爬山
原题链接
简单
作者:
tt2767
,
2019-12-23 22:41:51
,
所有人可见
,
阅读 1207
// dfs爆搜要怎么考虑?
// 1. dfs 的顺序 (1~ 一般是从1 or 0两种情况,即选或不选)
// 2. dfs 的递归状态,即参数
// 3. 剪枝 , 一个dfs常用的原则是“有限考虑决策少的元素”->"使根部的分支较少,子树变少,搜索空间大幅减少"
// (3~ 本题中优先考虑比较重的猫,因为选择比较少,很可能要新开车)
// 另cat,car 太容易写混了,建议换成别的。。。
import java.util.*;
public class Main{
void run(){
int n = jin.nextInt();
int w = jin.nextInt();
answer = n;
List<Integer> cats = new ArrayList<>();
for (int i = 0 ; i < n ; i++) cats.add(jin.nextInt());
System.out.println(solve(cats, w, n));
}
int solve(List<Integer> cats, int w, int n){
cats.sort((a,b)->(b-a));
dfs(0, 0, cats, w);
return answer;
}
void dfs(int curCat, int curCar, List<Integer> cats, int w){
if (curCar > answer) return;
if (curCat == cats.size()){
answer = curCar;
return;
}
int curWeight = cats.get(curCat);
for (int i = 0 ; i < curCar ;i++){
if (cars[i] + curWeight > w) continue;
cars[i] += curWeight;
dfs(curCat+1, curCar, cats, w);
cars[i] -= curWeight;
}
cars[curCar] += curWeight;
dfs(curCat+1, curCar+1, cats, w);
cars[curCar] -= curWeight;
}
private int answer;
private int[] cars = new int[18];
private Scanner jin = new Scanner(System.in);
public static void main(String[] args) throws Exception {new Main().run();}
}