本文共 1457 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要找到消耗原材料最多的生产线路,这可以通过求解图中的最长路径来实现。由于这是一个有向无环图(DAG),我们可以使用拓扑排序来处理每个节点,确保计算的正确性。
import sysfrom collections import dequedef main(): # 读取输入 input = sys.stdin.read().split() ptr = 0 N = int(input[ptr]) ptr += 1 M = int(input[ptr]) ptr += 1 # 初始化邻接表和入度数组 in_degree = [0] * (N + 1) adj = [[] for _ in range(N + 1)] # 邻接表,每个节点的邻居列表存储(目标节点,损耗) for _ in range(M): A = int(input[ptr]) ptr += 1 B = int(input[ptr]) ptr += 1 C = int(input[ptr]) ptr += 1 adj[A].append((B, C)) in_degree[B] += 1 # 初始化max_cost数组 max_cost = [0] * (N + 1) # 找出入度为0的节点作为起点 q = deque() for i in range(1, N + 1): if in_degree[i] == 0: q.append(i) # 拓扑排序并计算max_cost while q: u = q.popleft() for (v, cost) in adj[u]: if max_cost[v] < max_cost[u] + cost: max_cost[v] = max_cost[u] + cost in_degree[v] -= 1 if in_degree[v] == 0: q.append(v) # 找到max_cost中的最大值 print(max(max_cost))if __name__ == "__main__": main()
max_cost数组记录从起点到每个节点的最大损耗,q队列用于拓扑排序。max_cost中的最大值并输出。该方法确保了在处理每个节点时,所有可能影响其损耗的前驱节点已经被处理,从而保证了计算的正确性。
转载地址:http://pqnq.baihongyu.com/