AcWing DFS相关问题 165. 小猫爬山

import sys
sys.stdin = open('data.txt', 'r')


'''
先降序排序,然后递归枚举每一只猫放到哪辆车上,要么放在已经存在的车上,要么
重新加一辆车,放到新车上
'''


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])

 

你可能感兴趣的:(AcWing,DFS相关问题,算法)