(python)牛客周赛 Round 32

比赛链接:https://ac.nowcoder.com/acm/contest/75174#question

A.小红的01背包

思路:

V//x是看能装多少物品

再乘上每件物品的价格y就可以了

v,x,y = map(int,input().split())
print((v//x)*y)

B.小红的dfs

思路:

就是看每行每列不符合条件的有多少,先看第一行和第一列记录cnt1,再看第二行和第二列记录cnt2,再看第三行和第三列记录cnt3,看哪个符合条件最多。

list1 = []
for i in range(3):
    tmp = list(input())
    list1.append(tmp)
cnt1 = 0
cnt2 = 0
cnt3 = 0
if list1[0][0] != 'd': cnt1 += 1
if list1[0][1] != 'f': cnt1 += 1
if list1[0][2] != 's': cnt1 += 1
if list1[1][0] != 'f': cnt1 += 1
if list1[2][0] != 's': cnt1 += 1
if list1[1][0] != 'd': cnt2 += 1
if list1[1][1] != 'f': cnt2 += 1
if list1[1][2] != 's': cnt2 += 1
if list1[0][1] != 'd': cnt2 += 1
if list1[2][1] != 's': cnt2 += 1
if list1[2][0] != 'd': cnt3 += 1
if list1[2][1] != 'f': cnt3 += 1
if list1[2][2] != 's': cnt3 += 1
if list1[0][2] != 'd': cnt3 += 1
if list1[1][2] != 'f': cnt3 += 1
print(min(cnt1,cnt2,cnt3))

C.小红的排列生成

思路:

可以加1减1,先排列,那么我们只要看每次要达成条件每位的数应该如何变化就可以

n = int(input())
a = list(map(int,input().split()))
a.sort()
sum1 = 0
for i in range(1,n+1):
    sum1 += abs(i - a[i-1])
print(sum1)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
题目要求:给定一个二叉树和一个整数target,找出所有从根节点到叶子节点路径之和等于target的路径。 解题思路:可以使用深度优先搜索(DFS)的方法来解决该问题。首先定义一个辅助函数来进行递归搜索,该辅助函数的参数包括当前节点、当前路径、当前路径的和以及目标和。在搜索过程中,需要维护一个数组来保存当前节点到根节点的路径。搜索过程如下: 1. 如果当前节点为空,则返回。 2. 将当前节点的值添加到当前路径中。 3. 将当前节点的值累加到当前路径的和中。 4. 如果当前节点是叶子节点,且当前路径的和等于目标和,则将当前路径添加到结果中。 5. 递归地搜索当前节点的左子树和右子树,并传递更新后的当前路径和当前路径的和。 最后,在主函数中调用辅助函数,并返回结果即可。 以下是题目的完整代码实现: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def pathSum(root, target): def dfs(node, path, path_sum, target, res): if not node: return path.append(node.val) path_sum += node.val if not node.left and not node.right: # 当前节点是叶子节点 if path_sum == target: res.append(path[:]) # 注意需要复制一份path,否则会出现问题 dfs(node.left, path, path_sum, target, res) dfs(node.right, path, path_sum, target, res) path.pop() # 回溯到父节点,去掉当前节点 path_sum -= node.val res = [] dfs(root, [], 0, target, res) return res ``` 这样就能找出所有满足路径和等于目标和的路径了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值