From 2b93089f56765f3f48872e657a6c742e689c901f Mon Sep 17 00:00:00 2001 From: KaiserTT <116904940+KaiserTT@users.noreply.github.com> Date: Mon, 1 Jul 2024 13:06:09 +0800 Subject: [PATCH] add 0117 Java and Python --- problems/kamacoder/0117.软件构建.md | 101 +++++++++++++++++++++++- 1 file changed, 100 insertions(+), 1 deletion(-) diff --git a/problems/kamacoder/0117.软件构建.md b/problems/kamacoder/0117.软件构建.md index 5d1edf97..05cb7358 100644 --- a/problems/kamacoder/0117.软件构建.md +++ b/problems/kamacoder/0117.软件构建.md @@ -167,7 +167,7 @@ ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20240510114004.png) --------------- +-------------- 后面的过程一样的,节点3 和 节点4,入度都为0,选哪个都行。 @@ -344,8 +344,107 @@ int main() { ### Java +```java +import java.util.*; + + +public class Main { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int n = scanner.nextInt(); + int m = scanner.nextInt(); + + List> umap = new ArrayList<>(); // 记录文件依赖关系 + int[] inDegree = new int[n]; // 记录每个文件的入度 + + for (int i = 0; i < n; i++) + umap.add(new ArrayList<>()); + + for (int i = 0; i < m; i++) { + int s = scanner.nextInt(); + int t = scanner.nextInt(); + umap.get(s).add(t); // 记录s指向哪些文件 + inDegree[t]++; // t的入度加一 + } + + Queue queue = new LinkedList<>(); + for (int i = 0; i < n; i++) { + if (inDegree[i] == 0) { + // 入度为0的文件,可以作为开头,先加入队列 + queue.add(i); + } + } + + List result = new ArrayList<>(); + + // 拓扑排序 + while (!queue.isEmpty()) { + int cur = queue.poll(); // 当前选中的文件 + result.add(cur); + for (int file : umap.get(cur)) { + inDegree[file]--; // cur的指向的文件入度-1 + if (inDegree[file] == 0) { + queue.add(file); + } + } + } + + if (result.size() == n) { + for (int i = 0; i < result.size(); i++) { + System.out.print(result.get(i)); + if (i < result.size() - 1) { + System.out.print(" "); + } + } + } else { + System.out.println(-1); + } + } +} +``` + + + ### Python +```python +from collections import deque, defaultdict + +def topological_sort(n, edges): + inDegree = [0] * n # inDegree 记录每个文件的入度 + umap = defaultdict(list) # 记录文件依赖关系 + + # 构建图和入度表 + for s, t in edges: + inDegree[t] += 1 + umap[s].append(t) + + # 初始化队列,加入所有入度为0的节点 + queue = deque([i for i in range(n) if inDegree[i] == 0]) + result = [] + + while queue: + cur = queue.popleft() # 当前选中的文件 + result.append(cur) + for file in umap[cur]: # 获取该文件指向的文件 + inDegree[file] -= 1 # cur的指向的文件入度-1 + if inDegree[file] == 0: + queue.append(file) + + if len(result) == n: + print(" ".join(map(str, result))) + else: + print(-1) + + +if __name__ == "__main__": + n, m = map(int, input().split()) + edges = [tuple(map(int, input().split())) for _ in range(m)] + topological_sort(n, edges) +``` + + + ### Go ### Rust