diff --git a/cpp/2203/220316-CN.cpp b/cpp/2203/220316-CN.cpp new file mode 100644 index 0000000..42b2ff6 --- /dev/null +++ b/cpp/2203/220316-CN.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +#include +#include +#include + +class AllOne { +private: + int n = 0; + std::unordered_map id2Str; + std::unordered_map str2Id; + std::map> val2Id; + std::unordered_map id2Val; +public: + AllOne() = default; + + void inc(const std::string& key) { + if (str2Id.count(key)) { + int idx = str2Id[key]; + int& val = id2Val[idx]; + if (val2Id[val].size() == 1) { + val2Id.erase(val); + } else { + val2Id[val].erase(idx); + } + val2Id[++val].insert(idx); + } else { + int x = str2Id[key] = ++n; + id2Str[x] = key; + id2Val[x] = 1; + val2Id[1].insert(x); + } + } + + void dec(const std::string& key) { + int idx = str2Id[key]; + int& val = id2Val[idx]; + if (val == 1) { + id2Str.erase(idx); + if (val2Id[1].size() == 1) + val2Id.erase(1); + else + val2Id[1].erase(idx); + str2Id.erase(key); + id2Val.erase(idx); + } else { + if (val2Id[val].size() == 1) { + val2Id.erase(val); + } else { + val2Id[val].erase(idx); + } + val2Id[--val].insert(idx); + } + } + + std::string getMaxKey() { + return str2Id.empty() ? "" : id2Str[*(val2Id.rbegin()->second.begin())]; + } + + std::string getMinKey() { + return str2Id.empty() ? "" : id2Str[*(val2Id.begin()->second.begin())]; + } +}; + +int main() { + AllOne test; + test.inc("hello"); + test.inc("hello"); + std::cout << test.getMaxKey() << std::endl; + std::cout << test.getMinKey() << std::endl; + test.inc("123"); + std::cout << test.getMaxKey() << std::endl; + std::cout << test.getMinKey() << std::endl; + test.dec("hello"); + std::cout << test.getMaxKey() << std::endl; + std::cout << test.getMinKey() << std::endl; + test.dec("hello"); + std::cout << test.getMaxKey() << std::endl; + std::cout << test.getMinKey() << std::endl; +} diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index c5b6d19..30eaf5e 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220316.cpp) +ADD_EXECUTABLE(2203 220316-CN.cpp)