From c9be7ea9e750b79ecb38b86972ea5a602076dff2 Mon Sep 17 00:00:00 2001 From: Eatswap Date: Tue, 4 Apr 2023 02:17:16 +0800 Subject: [PATCH] add: 230403 --- cpp/2304/230403.cpp | 47 +++++++++++++++++++++++++++++++++++++++++ cpp/2304/CMakeLists.txt | 2 +- 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 cpp/2304/230403.cpp diff --git a/cpp/2304/230403.cpp b/cpp/2304/230403.cpp new file mode 100644 index 0000000..1e1d792 --- /dev/null +++ b/cpp/2304/230403.cpp @@ -0,0 +1,47 @@ +#include +#include +#include + +/** + * 881. Boats to Save People + * + * You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. + * Return the minimum number of boats to carry every given person. + */ + +class Solution { +public: + static int numRescueBoats(const std::vector& people, int limit) { + std::vector bucket(30005); + for (int i : people) + ++bucket[i]; + int ans = bucket[limit], i = 1, j = limit - 1, delta; + for (; i < j; --j) { + if (!bucket[j]) + continue; + while (bucket[j] && i + j <= limit && i < j) { + delta = std::min(bucket[j], bucket[i]); + bucket[j] -= delta; + bucket[i] -= delta; + ans += delta; + if (!bucket[i]) + ++i; + } + if (bucket[j]) { + if (i == j && i + j <= limit) + ans += (bucket[i] >> 1) + (bucket[i] & 1); + else + ans += bucket[j]; + } + bucket[j] = 0; + } + if (bucket[i]) + ans += (bucket[i] >> 1) + (bucket[i] & 1); + return ans; + } +}; + +int main() { + std::cout << Solution::numRescueBoats({2,2}, 6); + return 0; +} diff --git a/cpp/2304/CMakeLists.txt b/cpp/2304/CMakeLists.txt index 6fcecdc..5c8082e 100644 --- a/cpp/2304/CMakeLists.txt +++ b/cpp/2304/CMakeLists.txt @@ -4,4 +4,4 @@ PROJECT(2304) SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_EXPORT_COMPILE_COMMANDS true) -ADD_EXECUTABLE(2304 230402.cpp) +ADD_EXECUTABLE(2304 230403.cpp)