From 99ed7a59809e7afa676afb4079f2323b2f2f4595 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Wed, 6 Apr 2022 22:49:17 +0800 Subject: [PATCH] add: 220406-CN [cpp] --- cpp/2204/220406-CN.cpp | 76 +++++++++++++++++++++++++++++++++++++++++ cpp/2204/CMakeLists.txt | 2 +- 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 cpp/2204/220406-CN.cpp diff --git a/cpp/2204/220406-CN.cpp b/cpp/2204/220406-CN.cpp new file mode 100644 index 0000000..aae0d0c --- /dev/null +++ b/cpp/2204/220406-CN.cpp @@ -0,0 +1,76 @@ +#include +#include +#include + +class Solution { +public: + static std::vector findMinHeightTrees(int n, const std::vector>& edges) { + if (n == 1) + return {0}; + int degrees[n], ans[n]; + std::vector G[n]; + std::memset(degrees, 0, sizeof degrees); + std::memset(ans, 0, sizeof ans); + for (const auto& e : edges) { + G[e[0]].push_back(e[1]); + G[e[1]].push_back(e[0]); + ++degrees[e[0]]; + ++degrees[e[1]]; + } + + int x, y, distXY; + int father[n]; + { + int dist[n]; + bool vis[n]; + std::queue q; + + auto doBFS = [&](int startNode) { + q.push(startNode); + q.push(0); + std::memset(vis, 0, sizeof vis); + std::memset(father, 0, sizeof father); + vis[startNode] = true; + while (!q.empty()) { + int idx = q.front(); + q.pop(); + int len = q.front(); + q.pop(); + dist[idx] = len; + for (int nextId : G[idx]) { + if (vis[nextId]) + continue; + vis[nextId] = true; + father[nextId] = idx; + q.push(nextId); + q.push(len + 1); + } + } + }; + + // From 0, find the max distance + doBFS(0); + x = std::max_element(dist, dist + n) - dist; + + // From x, find the max distance + doBFS(x); + auto* maxDistPtr = std::max_element(dist, dist + n); + y = maxDistPtr - dist; + distXY = *maxDistPtr; + } + + std::vector ret; + int ptr = y; + for (int i = 0; i < distXY / 2; ++i) + ptr = father[ptr]; + ret.push_back(ptr); + if (distXY & 1) + ret.push_back(father[ptr]); + return ret; + } +}; + +int main() { + auto ret = Solution::findMinHeightTrees(2, {{0, 1}}); + return 0; +} diff --git a/cpp/2204/CMakeLists.txt b/cpp/2204/CMakeLists.txt index 94ac5e4..8642583 100644 --- a/cpp/2204/CMakeLists.txt +++ b/cpp/2204/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2204) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220405.cpp) +ADD_EXECUTABLE(2204 220406-CN.cpp)