Advertisement
pb_jiang

LC968 AC

Jan 25th, 2023
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13.     using pii = pair<int, int>;
  14.     using a3 = array<int, 3>;
  15.     a3 dfs2(TreeNode* node) {
  16.         if (node == nullptr) {
  17.             return {0, 0, INT_MAX / 2};
  18.         }
  19.         a3 ret = {0, 0, 0};
  20.         // ret[0]: all nodes below u are covered except u
  21.         // ret[1]: all nodes below u are covered, including u, and no camera at u
  22.         // ret[2]: all nodes below u are covered, including u, and there's a camera at u
  23.         auto child = vector<TreeNode*>{node->left, node->right};
  24.         int max_val = 0;
  25.         int min_delta = INT_MAX / 2;
  26.         for (auto v: child) {
  27.             auto [subtree, cover_noplace, cover_place] = dfs2(v);
  28.             ret[0] += cover_noplace;
  29.  
  30.             ret[1] += min(cover_noplace, cover_place);
  31.             max_val = max(max_val, cover_noplace);
  32.             min_delta = min(min_delta, cover_place - cover_noplace);
  33.            
  34.             ret[2] += min({subtree, cover_noplace, cover_place});
  35.         }
  36.         // ret[1] -= max_val;
  37.         if (min_delta > 0) ret[1] += min_delta;
  38.         ret[2] += 1;
  39.         printf("u:%p %d,%d,%d\n", node, ret[0], ret[1], ret[2]);
  40.         return ret;
  41.     }
  42. public:
  43.     int minCameraCover(TreeNode* root) {
  44.         auto ans = dfs2(root);
  45.         return min(ans[1], ans[2]);
  46.     }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement