-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0851-loud-and-rich.py
More file actions
42 lines (32 loc) · 1.09 KB
/
0851-loud-and-rich.py
File metadata and controls
42 lines (32 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# time complexity: O(v+e)
# space complexity: O(v+e)
from collections import deque
from typing import List
class Solution:
def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
n = len(quiet)
graph = [[] for _ in range(n)]
indegree = [0] * n
result = list(range(n))
for rich in richer:
graph[rich[0]].append(rich[1])
indegree[rich[1]] += 1
q = deque()
for i in range(n):
if indegree[i] == 0:
q.append(i)
while q:
node = q.popleft()
for neighbor in graph[node]:
if quiet[result[node]] < quiet[result[neighbor]]:
result[neighbor] = result[node]
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
q.append(neighbor)
return result
richer = [[1, 0], [2, 1], [3, 1], [3, 7], [4, 3], [5, 3], [6, 3]]
quiet = [3, 2, 5, 4, 6, 1, 7, 0]
print(Solution().loudAndRich(richer, quiet))
richer = []
quiet = [0]
print(Solution().loudAndRich(richer, quiet))