代码改变世界

[LeetCode] 851. Loud and Rich_ Medium tag: DFS

2018-07-13 04:55  Johnson_强生仔仔  阅读(397)  评论(0编辑  收藏  举报

In a group of N people (labelled 0, 1, 2, ..., N-1), each person has different amounts of money, and different levels of quietness.

For convenience, we'll call the person with label x, simply "person x".

We'll say that richer[i] = [x, y] if person x definitely has more money than person y.  Note that richer may only be a subset of valid observations.

Also, we'll say quiet[x] = q if person x has quietness q.

Now, return answer, where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]), among all people who definitely have equal to or more money than person x.

 

Example 1:

Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]
Output: [5,5,2,5,4,5,6,7]
Explanation: 
answer[0] = 5.
Person 5 has more money than 3, which has more money than 1, which has more money than 0.
The only person who is quieter (has lower quiet[x]) is person 7, but
it isn't clear if they have more money than person 0.

answer[7] = 7.
Among all people that definitely have equal to or more money than person 7
(which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x])
is person 7.

The other answers can be filled out with similar reasoning.

Note:

  1. 1 <= quiet.length = N <= 500
  2. 0 <= quiet[i] < N, all quiet[i] are different.
  3. 0 <= richer.length <= N * (N-1) / 2
  4. 0 <= richer[i][j] < N
  5. richer[i][0] != richer[i][1]
  6. richer[i]'s are all different.
  7. The observations in richer are all logically consistent.

 

这个题目的思路就是将richer转换为graph, 然后是由穷的往富的走, 因为穷的subtree更多, 所以可以直接利用富的quietest, 然后跟自身进行比较即可, 只不过除了graph之外还有一个quiet, 实际上就像一个dictionary of value.

 

1. Constraints

1) quite.length = [1,500], so not empty

2) 0 <= quiet[i] < N, all quiet[i] are different., no duplicates

3) richer and element will be valiad and no duplicates, all logivally consistent, no loop in the graph

 

2. Ideas

DFS      : T: O(n)    S: O(n)

1) 得到N, 初始化ans

2)将richer 转换为graph

3) 利用dfs, 只不过利用post order的顺序, 可以利用ans来cache 之前的结果, 确实很巧妙

4) for loop 将所有点都scan一遍, 返回最后的ans

 

3. Code

 1 class Solution:
 2     def loudRich(self, richer, quiet):
 3         N, graph = len(quiet), collections.defaultdict(set)
 4         ans = [None]*N
 5         for x, y in richer:
 6             graph[y].add(x)
 7         def dfs(i):
 8             if ans[i] == None:
 9                 ans[i] = i
10                 for each in graph[i]:
11                     cand = dfs(each)
12                     if quiet[cand] < quiet[ans[i]]:
13                         ans[i] = cand
14             return ans[i]
15         for i in range(N):
16             dfs(i)
17         return ans

 

4. test case

richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]