题目链接:
力扣https://leetcode-cn.com/problems/count-nodes-with-the-highest-score/
【分析】这道题目删去一个节点后,组成的子树可能是父节点的那一堆,以及自己的两个儿子组成的两个子树(可能没有)。所以如果能统计出以每个节点为根节点组成的子树所含节点的个数这个问题就迎刃而解了。
由于题目给的是父节点信息,我们需要用一个链表数组来统计每个节点的孩子们。然后dfs遍历统计节点个数即可,可以用数组进行记忆化,防止重复搜索。
class Solution {
int n;
// Map<Integer, List<Integer>> map = new HashMap<>();
List<Integer>[] map;
int[] cnt;
public int dfs(int i){
if(cnt[i] != -1) return cnt[i];
int ret = 0;
for(Integer it: map[i]){
if(cnt[it] != -1) ret += cnt[it];
else ret += dfs(it);
}
cnt[i] = ret + 1;
return cnt[i];
}
public int countHighestScoreNodes(int[] parents) {
int ans = 0;
n = parents.length;
cnt = new int[n];
Arrays.fill(cnt, -1);
int i;
map = new ArrayList[n];
for(i = 0; i < n; i++){
map[i] = new ArrayList<>();
}
for(i = 1; i < n; i++){
map[parents[i]].add(i);
}
for(i = 0; i < n; i++){
dfs(i);
}
for(i = 0; i < n; i++){
System.out.print(cnt[i]);
System.out.print(" ");
}
System.out.println();
long max = -1;
long a = 1;
for(Integer it: map[0]){
a *= cnt[it];
}
if(a > max){
max = a;
ans++;
}
for(i = 1; i < n; i++){
a = 1;
for(Integer it: map[i]) a *= cnt[it];
a *= (cnt[0] - cnt[i]);
System.out.println(a);
if(a > max){
max = a;
ans = 1;
}else if(a == max){
ans++;
}
}
// System.out.println(max);
System.out.println(ans);
return ans;
}
}