AcWing 165. 小猫爬山 简单DFS爆搜
原题链接
简单
作者:
皓首不倦
,
2020-08-04 00:15:19
,
所有人可见
,
阅读 658
'''
先降序排序,然后递归枚举每一只猫放到哪辆车上,要么放在已经存在的车上,要么
重新加一辆车,放到新车上
'''
arr = []
n, w = map(int, input().split())
for i in range(n):
arr.append(int(input()))
arr.sort(reverse=True)
sum_weight = [0] * 20
ans = [0x7fffffff]
# cur_idx 表示当前在枚举的数的下标 group_num是当前已经有的组的数量
def dfs(cur_idx, group_num):
if group_num >= ans[0]:
return
if cur_idx == n:
ans[0] = min(ans[0], group_num)
return
new_val = arr[cur_idx]
for i in range(group_num):
if sum_weight[i] + new_val <= w:
sum_weight[i] += new_val
dfs(cur_idx+1, group_num)
sum_weight[i] -= new_val
sum_weight[group_num] += new_val
dfs(cur_idx+1, group_num+1)
sum_weight[group_num] -= new_val
dfs(0, 1)
print(ans[0])