[LeetCode] Count Nodes With the Highest Score

2049. Count Nodes With the Highest Score

There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1.

Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees.

Return the number of nodes that have the highest score.

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
class Solution {
vector<vector<int>> adj;
vector<int> sub;
int dfs(int u) {
int& res = sub[u] = 1;
for(auto& v : adj[u]) {
res += dfs(v);
}
return res;
}
long long query(int u, int n) {
long long res = 1, rem = n - 1;
for(auto& v : adj[u]) {
res *= sub[v];
rem -= sub[v];
}
if(rem) res *= rem;
return res;
}
public:
int countHighestScoreNodes(vector<int>& par) {
adj = vector<vector<int>>(par.size());
sub = vector<int>(par.size());
for(int i = 0; i < par.size(); i++) {
if(par[i] == -1) continue;
adj[par[i]].push_back(i);
}
dfs(0);
long long ma = -1, cnt = 0;
for(int i = 0; i < par.size(); i++) {
long long now = query(i,par.size());
if(ma == now) cnt++;
else if(ma < now) {
ma = now;
cnt = 1;
}
}

return cnt;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/10/PS/LeetCode/count-nodes-with-the-highest-score/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.