dfs?背包?动态规划?dfs减枝!

这个题目还是比较好拿分的,其实要想清楚,一个瓜如果被劈开了,那么一定只会用到一半

这个问题可以理解为拿与不拿问题,我们可以写一个子集回溯的问题,见下面第一个代码
但是有很多测试集超时了,我其实想写一个背包,但是值域范围到了 1 0 9 10^9 109,没办法写成背包,而且也难以写成动态规划

那我们只能dfs加上剪枝


from math import inf
# 如果不需要劈瓜,那就是一个简单背包问题,


n,m = map(int,input().split())
a = list(map(int,input().split()))

ans = inf

def dfs(now,cnt,index):
  if now == m:
    global ans
    ans = min(ans,cnt)
    return
  if index >= n:
    return
  for i in range(index,n):
    if a[i] + now <= m:
      dfs(now+a[i],cnt,i+1)
    if a[i]/2 + now <=m:
      dfs(now+a[i]/2,cnt+1,i+1)

dfs(0.0,0,0)
if ans != inf:
  print(ans)
else:
  print(-1)

如何去优化这个题目呢?
首先我们要先把西瓜按照大到小进行一个排序,这样十分有助于我们快速排除一个非法的情况
我们再维护一个后缀和,我们当前西瓜的重量如果加上后缀的西瓜的总重量还是达不到我们的目标,就剪枝

但是这个只能过95%

import os
import sys

# 请在此输入您的代码
from math import inf
# 如果不需要劈瓜,那就是一个简单背包问题,


n,m = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)

hou = [0]*(n)
hou[-1] = a[-1]
for i in range(n-2,-1,-1):
  hou[i] += hou[i+1] + a[i]
ans = inf

def dfs(now,cnt,index):
  if now == m:
    global ans
    ans = min(ans,cnt)
    return
  if index >= n:
    return
  for i in range(index,n):
    if a[i] + now <= m and hou[i]+now>=m:
      dfs(now+a[i],cnt,i+1)
    if a[i]/2 + now <=m and now+hou[i]-a[i]/2>=m:
      dfs(now+a[i]/2,cnt+1,i+1)

dfs(0.0,0,0)
if ans != inf:
  print(ans)
else:
  print(-1)

我的这个dfs写法是枚举的是方案,不如写成枚举每一位

这个可以过全部的

import os
import sys

# 请在此输入您的代码
from math import inf
# 如果不需要劈瓜,那就是一个简单背包问题,


n,m = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)

hou = [0]*(n)
hou[-1] = a[-1]
for i in range(n-2,-1,-1):
  hou[i] += hou[i+1] + a[i]
ans = inf

def dfs(now,cnt,index):
  if now == m:
    global ans
    ans = min(ans,cnt)
    return
  if index >= n or now >m:
    return
  if now+hou[index]<m:
    return
  # 注意选与不选
  dfs(now,cnt,index+1)
  dfs(now+a[index],cnt,index+1)
  dfs(now+a[index]/2,cnt+1,index+1)

dfs(0.0,0,0)
if ans != inf:
  print(ans)
else:
  print(-1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wniuniu_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值