本题只能用按小猫枚举来dfs
思路:
1,小猫加入到老的缆车
2,小猫加入到新的缆车
一开始我按缆车来枚举, 其实枚举不到最小值。
代码
import java.io.*;
class Main{
static int N = 20, n, ans;
static int w;
static int[] a = new int[N], groupNum = new int[N];
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args ) throws Exception{
String[] ss = read.readLine().split(" ");
n = Integer.valueOf(ss[0]);
ans = n;
w = Integer.valueOf(ss[1]);
for(int i = 0; i < n; i++){
a[i] = Integer.valueOf(read.readLine());
}
dfs(0, 0, 0);
System.out.println(ans);
}
//按猫枚举
public static void dfs(int cur, int totalCnt, int maxGroup){
if(totalCnt == n) {
ans = Math.min(ans, maxGroup);
}
if(maxGroup >= ans || cur >= n) return;
//加入之前的组
for(int i = 1; i <= maxGroup; i++){
int nw = groupNum[i] + a[cur];
if(nw <= w){
groupNum[i] = nw;
dfs(cur + 1, totalCnt + 1, maxGroup);
groupNum[i] -= a[cur];
}
}
//加入到新建的组
groupNum[maxGroup + 1] += a[cur];
dfs(cur + 1, totalCnt + 1, maxGroup + 1);
groupNum[maxGroup + 1] -= a[cur];
}
}
按缆车来枚举, 为啥枚举不到最小值