From 835292dbb618556c8e26fc3047122468bfd17016 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Thu, 6 Jan 2022 09:16:41 +0800 Subject: [PATCH] add: 220106 --- 2201/220106.cpp | 68 +++++++++++++++++++++++++++++++++++++++++++++ 2201/CMakeLists.txt | 2 +- 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 2201/220106.cpp diff --git a/2201/220106.cpp b/2201/220106.cpp new file mode 100644 index 0000000..129cbd6 --- /dev/null +++ b/2201/220106.cpp @@ -0,0 +1,68 @@ +#include +#include + +/** + * 1094. Car Pooling + * There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). + * + * You are given the integer capacity and an array trips where trip[i] = [numPassengers[i], from[i], to[i]] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. + * + * Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise. + */ + +struct Node { + const std::vector* const data; + Node* next; + Node(const std::vector* const data, Node* next) : data(data), next(next) {} + ~Node() { delete this->next; } +}; + +class SolutionOld { +public: + static bool carPooling(const std::vector>& trips, int capacity) { + Node* bucket[1005]{}; + for (const auto& i : trips) { + bucket[i[1]] = new Node(&i, bucket[i[1]]); + bucket[i[2]] = new Node(&i, bucket[i[2]]); + } + int current = 0; + bool ok = true; + for (int i = 0; i <= 1000; ++i) { + for (Node* ptr = bucket[i]; ptr; ptr = ptr->next) { + if ((*ptr->data)[1] == i) { // pick up + current += (*ptr->data)[0]; + } else { // drop off + current -= (*ptr->data)[0]; + } + } + if (current > capacity) { + ok = false; + break; + } + } + for (int i = 0; i <= 1000; ++i) + delete bucket[i]; + return ok; + } +}; + +class Solution { +public: + static bool carPooling(const std::vector>& trips, int capacity) { + int change[1005]{}; + for (const auto& i : trips) { + change[i[1]] += i[0]; + change[i[2]] -= i[0]; + } + int current = 0; + for (int i = 0; i <= 1000; ++i) + if (capacity < (current += change[i])) + return false; + return true; + } +}; + +int main() { + std::cout << Solution::carPooling({{2,1,5},{3,3,7}}, 5) << std::endl; + return 0; +} \ No newline at end of file diff --git a/2201/CMakeLists.txt b/2201/CMakeLists.txt index 106d2b6..5318f89 100644 --- a/2201/CMakeLists.txt +++ b/2201/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2201) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2201 220106-CN.cpp) \ No newline at end of file +ADD_EXECUTABLE(2201 220106.cpp) \ No newline at end of file