From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- other/min_time_apples_tree.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 other/min_time_apples_tree.cpp (limited to 'other/min_time_apples_tree.cpp') diff --git a/other/min_time_apples_tree.cpp b/other/min_time_apples_tree.cpp new file mode 100644 index 0000000..81d97d7 --- /dev/null +++ b/other/min_time_apples_tree.cpp @@ -0,0 +1,39 @@ +#include "leetcode.h" + +class Solution { +public: + int minTime(int n, vvd & edges, vector &hasApple) { + unordered_map 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 edges = {{0, 1}, {0, 2}, {1, 4}, {1, 5}, {2, 3}, {2, 6}}; + vector 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 +} -- cgit v1.2.3