From f45b13256cf3fa5f70fc0e7e2409067e9ba4c6ff Mon Sep 17 00:00:00 2001 From: Won Joon Thomas Choi <113500771+724thomas@users.noreply.github.com> Date: Sat, 5 Sep 2026 23:53:44 +0900 Subject: [PATCH] Create 851. Loud and Rich.py --- .../851. Loud and Rich.py" | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 "leetcode3/\354\265\234\354\233\220\354\244\200/851. Loud and Rich.py" diff --git "a/leetcode3/\354\265\234\354\233\220\354\244\200/851. Loud and Rich.py" "b/leetcode3/\354\265\234\354\233\220\354\244\200/851. Loud and Rich.py" new file mode 100644 index 00000000..306ed440 --- /dev/null +++ "b/leetcode3/\354\265\234\354\233\220\354\244\200/851. Loud and Rich.py" @@ -0,0 +1,31 @@ +class Solution: + def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: + n = len(quiet) + + graph = [[] for _ in range(n)] + + for rich, poor in richer: + graph[poor].append(rich) + + answer = [-1] * n + + def dfs(x): + # 이미 계산했다면 재사용 + if answer[x] != -1: + return answer[x] + + # 자기 자신도 후보 + answer[x] = x + + for rich in graph[x]: + candidate = dfs(rich) + + if quiet[candidate] < quiet[answer[x]]: + answer[x] = candidate + + return answer[x] + + for i in range(n): + dfs(i) + + return answer