Skip to content

Commit 8f66f25

Browse files
authored
Create count-nodes-with-the-highest-score.cpp
1 parent 047a593 commit 8f66f25

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int countHighestScoreNodes(vector<int>& parents) {
7+
vector<vector<int>> adj(size(parents)); // Space: O(n)
8+
for (int i = 1; i < size(parents); ++i) {
9+
adj[parents[i]].emplace_back(i);
10+
}
11+
return iter_dfs(adj);
12+
}
13+
private:
14+
int iter_dfs(const vector<vector<int>>& adj) {
15+
pair<int64_t, int> result;
16+
using RET = shared_ptr<int>;
17+
auto ret = make_shared<int>();
18+
vector<tuple<int, int, vector<RET>, RET>> stk;
19+
stk.emplace_back(1, 0, vector<RET>(), ret);
20+
while (!empty(stk)) {
21+
auto [step, i, cnts, ret] = stk.back(); stk.pop_back();
22+
if (step == 1) {
23+
vector<RET> cnts(size(adj[i]));
24+
for (auto& cnt : cnts) {
25+
cnt = make_shared<int>();
26+
}
27+
stk.emplace_back(2, i, cnts, ret);
28+
for (int j = 0; j < size(adj[i]); ++j) {
29+
stk.emplace_back(1, adj[i][j], vector<RET>(), cnts[j]);
30+
}
31+
} else if (step == 2) {
32+
*ret = accumulate(cbegin(cnts), cend(cnts), 0,
33+
[](const auto& total, const auto& x) {
34+
return total + *x;
35+
}) + 1;
36+
const int64_t score = max(static_cast<int64_t>(size(adj)) - *ret, 1l) *
37+
accumulate(cbegin(cnts), cend(cnts), 1ul,
38+
[](const auto& total, const auto& x) {
39+
return total * *x;
40+
});
41+
if (score > result.first) {
42+
result = {score, 1};
43+
} else if (score == result.first) {
44+
++result.second;
45+
}
46+
}
47+
}
48+
return result.second;
49+
}
50+
};
51+
52+
// Time: O(n)
53+
// Space: O(n)
54+
class Solution2 {
55+
public:
56+
int countHighestScoreNodes(vector<int>& parents) {
57+
vector<vector<int>> adj(size(parents)); // Space: O(n)
58+
for (int i = 1; i < size(parents); ++i) {
59+
adj[parents[i]].emplace_back(i);
60+
}
61+
pair<int64_t, int> result;
62+
dfs(adj, 0, &result);
63+
return result.second;
64+
}
65+
private:
66+
int dfs(const vector<vector<int>>& adj, int i, pair<int64_t, int> *result) {
67+
vector<int> cnts;
68+
for (const auto& child : adj[i]) {
69+
cnts.emplace_back(dfs(adj, child, result));
70+
}
71+
const int total = accumulate(cbegin(cnts), cend(cnts), 0) + 1;
72+
const int64_t score = max(static_cast<int64_t>(size(adj)) - total, 1l) *
73+
accumulate(cbegin(cnts), cend(cnts), 1ul,
74+
[](const auto& total, const auto& x) {
75+
return total * x;
76+
});
77+
if (score > result->first) {
78+
*result = {score, 1};
79+
} else if (score == result->first) {
80+
++result->second;
81+
}
82+
return total;
83+
}
84+
};

0 commit comments

Comments
 (0)