Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- using pii = pair<int, int>;
- using a3 = array<int, 3>;
- pii dfs(TreeNode* node) {
- // cost of subtree covered exculte itself,
- // cost of subtree covered all
- pii ret = {0, 1};
- auto child = vector<TreeNode*>{node->left, node->right};
- for (auto v: child) {
- auto [x, y] = dfs(v);
- }
- return ret;
- }
- pii dfs1(TreeNode* node) {
- // cover by itself, cover by its child
- pii ret = {1, INT_MAX / 2};
- int min_delta = INT_MAX / 2;
- int child_cost = 0;
- auto child = vector<TreeNode*>{node->left, node->right};
- for (auto v: child) {
- if (v == nullptr) continue;
- auto [self_cover, child_cover] = dfs1(v);
- child_cost += min(self_cover, child_cover);
- min_delta = min(min_delta, child_cover - self_cover);
- }
- ret.first += child_cost;
- ret.second += child_cost + (min_delta < 0 ? 0 : min_delta);
- return ret;
- }
- a3 dfs2(TreeNode* node) {
- a3 ret = {0, INT_MAX / 2, 1};
- auto child = vector<TreeNode*>{node->left, node->right};
- int min_delta = INT_MAX / 2;
- for (auto v: child) {
- if (v == nullptr) continue;
- auto [subtree, cover_noplace, cover_place] = dfs2(v);
- ret[2] += min({subtree, cover_noplace, cover_place});
- ret[1] += min(cover_noplace, cover_place);
- min_delta = min(min_delta, cover_place - cover_noplace);
- ret[0] += cover_noplace;
- }
- if (min_delta > 0) ret[1] += min_delta;
- return ret;
- }
- public:
- int minCameraCover(TreeNode* root) {
- auto ans = dfs2(root);
- return min(ans[1], ans[2]);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement