Python快速开租建站

B站影视 2025-01-05 04:54 3

摘要:from collections import dequedef minimum_start_time(taskNum, relations):# 构建图和入度数组graph = {i: for i in range(taskNum)}in_degree =

from collections import dequedef minimum_start_time(taskNum, relations):# 构建图和入度数组graph = {i: for i in range(taskNum)}in_degree = [0] * taskNumfor u, v in relations:graph[u].append(v)in_degree[v] += 1# 队列存储入度为0的任务queue = dequeearliest_time = [0] * taskNum # 每个任务完成的最早时间for i in range(taskNum):if in_degree[i] == 0:queue.append(i)# 拓扑排序 + 计算最短时间while queue:current = queue.popleftfor neighbor in graph[current]:in_degree[neighbor] -= 1# 更新依赖任务的最早时间earliest_time[neighbor] = max(earliest_time[neighbor], earliest_time[current] + 1)if in_degree[neighbor] == 0:queue.append(neighbor)# 返回所有任务完成所需的最大时间return max(earliest_time) + 1 # +1表示从时间0开始计时if __name__ == "__main__":# 自定义输入taskNum = int(input("请输入任务数 taskNum: "))relationsNum = int(input("请输入依赖关系数 relationsNum: "))relations = print("请输入每个依赖关系(格式: IDi IDj,表示任务 IDi 是任务 IDj 的前置任务):")for _ in range(relationsNum):u, v = map(int, input.split)relations.append((u, v))# 输出结果result = minimum_start_time(taskNum, relations)print(f"一个站点的最短启动时间为: {result}")

来源:科技深观察

相关推荐