diff options
author | crupest <crupest@outlook.com> | 2020-09-22 17:14:18 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2020-09-22 17:14:18 +0800 |
commit | badc6cc5faca45d15728fa0dcc3cefc9e9d36f34 (patch) | |
tree | e529445ee5e2549d14d08213d3aa1e7ae7fd9781 /works | |
parent | 6b2a26fa6f289fce86c72f6992387dea20646347 (diff) | |
download | crupest-badc6cc5faca45d15728fa0dcc3cefc9e9d36f34.tar.gz crupest-badc6cc5faca45d15728fa0dcc3cefc9e9d36f34.tar.bz2 crupest-badc6cc5faca45d15728fa0dcc3cefc9e9d36f34.zip |
import(solutions): Add problem 968 .
Diffstat (limited to 'works')
-rw-r--r-- | works/solutions/cpp/968.cpp | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/works/solutions/cpp/968.cpp b/works/solutions/cpp/968.cpp new file mode 100644 index 0000000..4feecf6 --- /dev/null +++ b/works/solutions/cpp/968.cpp @@ -0,0 +1,63 @@ +#include <cstddef> + +struct TreeNode +{ + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +#include <algorithm> + +struct Result +{ + // root_camera >= root_monitored >= root_not_monitored + int root_camera; + int root_monitored; + int root_not_monitored; +}; + +class Solution +{ +public: + Result dfs(TreeNode *root) + { + if (root->left == nullptr && root->right == nullptr) + { + return Result{1, 1, 0}; + } + + if (root->left == nullptr || root->right == nullptr) + { + TreeNode *child_node = root->left == nullptr ? root->right : root->left; + Result child = dfs(child_node); + + int root_camera = 1 + child.root_not_monitored; + int root_monitored = std::min({child.root_camera, + root_camera}); + int root_not_monitored = std::min(child.root_monitored, root_monitored); + + return Result{ + root_camera, root_monitored, root_not_monitored}; + } + + Result left = dfs(root->left); + Result right = dfs(root->right); + + int root_camera = 1 + left.root_not_monitored + right.root_not_monitored; + int root_monitored = std::min({left.root_camera + right.root_monitored, + left.root_monitored + right.root_camera, + root_camera}); + int root_not_monitored = std::min({left.root_monitored + right.root_monitored, root_monitored}); + + return Result{ + root_camera, root_monitored, root_not_monitored}; + } + + int minCameraCover(TreeNode *root) + { + auto result = dfs(root); + return result.root_monitored; + } +};
\ No newline at end of file |