From 915e9e6ca2d9dea82cb4c1975c7e43a2095c2de7 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Fri, 11 Mar 2022 11:06:35 +0800 Subject: [PATCH] add: 220311-CN [cpp] --- cpp/2203/220311-CN.cpp | 55 +++++++++++++++++++++++++++++++++++++++++ cpp/2203/CMakeLists.txt | 2 +- 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 cpp/2203/220311-CN.cpp diff --git a/cpp/2203/220311-CN.cpp b/cpp/2203/220311-CN.cpp new file mode 100644 index 0000000..161bb80 --- /dev/null +++ b/cpp/2203/220311-CN.cpp @@ -0,0 +1,55 @@ +#include +#include +#include + +class Solution { +public: + static int countHighestScoreNodes(const std::vector& parents) { + auto n = parents.size(); + int* L = new int[n]{}; + int* R = new int[n]{}; + int* sizeOfSubtrees = new int[n]{}; + + for (int i = 1; i < n; ++i) + *(L[parents[i]] ? &R[parents[i]] : &L[parents[i]]) = i; + + std::function getSubtreeSize = [&](int node) { + if (sizeOfSubtrees[node]) + return sizeOfSubtrees[node]; + int ret = 1; + if (L[node]) + ret += getSubtreeSize(L[node]); + if (R[node]) + ret += getSubtreeSize(R[node]); + return sizeOfSubtrees[node] = ret; + }; + + unsigned long long retMax = 0; + int ret = -1; + for (int i = 0; i < n; ++i) { + int sizeL = 0, sizeR = 0, sizeOther = n - 1; + if (L[i]) + sizeOther -= (sizeL = getSubtreeSize(L[i])); + if (R[i]) + sizeOther -= (sizeR = getSubtreeSize(R[i])); + auto size = static_cast(sizeL ? sizeL : 1) * static_cast(sizeR ? sizeR : 1) * static_cast(sizeOther ? sizeOther : 1); + if (retMax < size) { + retMax = size; + ret = 1; + } else if (retMax == size) { + ++ret; + } + } + + delete[] L; + delete[] R; + delete[] sizeOfSubtrees; + + return ret; + } +}; + +int main() { + std::cout << Solution::countHighestScoreNodes({-1,2,0}); + return 0; +} diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index cb64caf..1170890 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220310.cpp) +ADD_EXECUTABLE(2203 220311-CN.cpp)