题目案例解释
图中线段上数字为生长所需时间,圈内数字为植物编号。
思路:
一:对于得到第i号植物所需的时间由两部分因素影响:
1.两个子节点生长所需的时间取最大值
2.通过得到两个子节点所需的时间取最大值
因为两个子节点可以同时杂交,所以只需要取两个子节点杂交所需时间的最大值,就是花费时间较长的子节点杂交完成后,则花费时间较短的子节点一定也杂交完成了,因为时间足够。所以只需要取两者的最大值。
二:由于每一个植物可以有多种方案杂交获得,所以我们还需要遍历每一种方案,取时间最短的方案
三:基于以上思路我们需要用到的有一个列表来记录得到i号植物所需的最短时间
四:分析题目输入
n, m, k, t = map(int, input().split())
输入植物种类,初始拥有植物的数量,杂交的方案数,目标植物编号
plant_grow_time = [0] # i号植物生长的时间
plant_grow_time += list(map(int, input().split()))
为了方便理解,将0号植物的位置留出
min_grow_time = [math.inf] * (n + 1) # 得到i号植物的最小所需时间,因为要取最小值,初始化为较大值 have_plant = [False] * (n + 1) # 是否已经计算过得到i号植物的所需时间
for i in map(int, input().split()): min_grow_time[i] = 0 # 初始拥有则得到它的最小时间为0 have_plant[i] = True # 标记为已经计算过
输入初始拥有的植物
plans = {} # 杂交方案 for _ in range(k): child_left, child_right, i = map(int, input().split()) # 两个子节点和i号植物 if i not in plans.keys(): # 如果原来的杂交方案里没有得到i号植物的方案 plans[i] = [] # 初始化方案列表,可能有多个方案得到i号植物,所以设为列表 plans[i].append([child_left, child_right])
# 测试案例plans为: {3: [[1, 2]], 4: [[1, 3]], 5: [[2, 3]], 6: [[4, 5]]}
dfs(t) # 查询目标节点 print(min_grow_time[t]) # 输出目标节点的最短时间
接下来就是需要构造一个dfs()可以查询出得到i号植物所需的最短时间
dfs() 伪代码:
def dfs(需要查询最短得到时间的第i号植物):
if 该植物已经计算过最短得到时间:
return min_grow_time[i]
遍历每一种杂交得到i号植物的方案,找到最短时间的方案并保存进min_grow_time[i]
return 计算得到的第i号植物的最短时间
代码:
import math def dfs(now_plant): if have_plant[now_plant]: # 如果now_plant已经计算过 return min_grow_time[now_plant] for plan in plans[now_plant]: # 遍历每一种方案 plan_need_time = max(plant_grow_time[plan[0]], plant_grow_time[plan[1]]) + max(dfs(plan[0]), dfs(plan[1])) # max(plant_grow_time[plan[0]], plant_grow_time[plan[1]]) 是指取两个子节点生长的最大值 # max(dfs(plan[0]), dfs(plan[1])) 是指取得到两个子节点的最大值,在思路里已经过解释为什么是最大值 min_grow_time[now_plant] = min(min_grow_time[now_plant], plan_need_time) # 对于每一种方案都保持min_grow_time里的时间最短 # for循环结束就是遍历了可以得到i号植物的所有方案,并且找到了其中用时最短的方案存入了min_grow_time里 have_plant[now_plant] = True # 将第i号植物设为已经计算过 return min_grow_time[now_plant] # 返回得到第i号植物最短用时 if __name__ == '__main__': n, m, k, t = map(int, input().split()) plant_grow_time = [0] # 植物生长的时间 plant_grow_time += list(map(int, input().split())) min_grow_time = [math.inf] * (n + 1) # i号植物的最小所需时间 have_plant = [False] * (n + 1) # 是否已经计算过i号植物的所需时间 for i in map(int, input().split()): min_grow_time[i] = 0 have_plant[i] = True plans = {} # 杂交方案 for _ in range(k): child_left, child_right, i = map(int, input().split()) if i not in plans.keys(): plans[i] = [] plans[i].append([child_left, child_right]) dfs(t) print(min_grow_time[t])