aboutsummaryrefslogtreecommitdiff
path: root/min_time_apples_tree.cpp
diff options
context:
space:
mode:
authorjack <0x6A73@pm.me>2024-06-14 13:13:15 -0600
committerjack <0x6A73@pm.me>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /min_time_apples_tree.cpp
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'min_time_apples_tree.cpp')
-rw-r--r--min_time_apples_tree.cpp39
1 files changed, 39 insertions, 0 deletions
diff --git a/min_time_apples_tree.cpp b/min_time_apples_tree.cpp
new file mode 100644
index 0000000..9e9d4b4
--- /dev/null
+++ b/min_time_apples_tree.cpp
@@ -0,0 +1,39 @@
+#include "leetcode.h"
+
+class Solution {
+public:
+ int minTime(int n, vvd(int) & edges, vector<bool> &hasApple) {
+ unordered_map<int, int> um;
+ int ans = 0;
+ sort(edges.begin(), edges.end());
+ for (auto const &e : edges) {
+ if (um.count(e[1]) > 0)
+ um[e[0]] = e[1];
+ else
+ um[e[1]] = e[0];
+ }
+ for (int i = 0; i < hasApple.size(); ++i) {
+ if (!hasApple[i])
+ continue;
+ int parent = i;
+ while (parent != 0 && um[parent] >= 0) {
+ auto tmp = um[parent];
+ um[parent] = -1;
+ parent = tmp;
+ ans += 2;
+ }
+ }
+ return ans;
+ }
+};
+
+int main() {
+ Solution obj;
+ vvd(int) edges = {{0, 1}, {0, 2}, {1, 4}, {1, 5}, {2, 3}, {2, 6}};
+ vector<bool> hasApple1 = {false, false, true, false, true, true, false},
+ hasApple2 = {false, false, true, false, false, true, false},
+ hasApple3 = {false, false, false, false, false, false, false};
+ cout << obj.minTime(7, edges, hasApple1) << endl; // expect: 8
+ cout << obj.minTime(7, edges, hasApple2) << endl; // expect: 6
+ cout << obj.minTime(7, edges, hasApple3) << endl; // expect: 0
+}