From 7cc71916e30985cc70927675ae37cf17e25ec717 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Sat, 8 Jan 2022 01:03:33 +0800 Subject: [PATCH] add: 220108-CN --- 2201/220108-CN.cpp | 69 +++++++++++++++++++++++++++++++++++++++++++++ 2201/CMakeLists.txt | 2 +- CMakeLists.txt | 1 + 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 2201/220108-CN.cpp diff --git a/2201/220108-CN.cpp b/2201/220108-CN.cpp new file mode 100644 index 0000000..e0310d5 --- /dev/null +++ b/2201/220108-CN.cpp @@ -0,0 +1,69 @@ +#include +#include +#include + +class Solution { +public: + static std::vector grayCode(const int n) { + std::vector ret{0}; + for (int i = 0; i < n; ++i) { + ret.insert(ret.end(), ret.rbegin(), ret.rend()); + for (int j = 1 << i; j < (1 << (1 + i)); ++j) + ret[j] |= (1 << i); + } + return ret; + } +}; + +class SolutionOld { +public: + static std::vector grayCode(const int n) { + int lim = 1 << n, cur = 0; + std::vector ret{0}; + ret.reserve(lim); + int* const vis = new int[1 + (lim >> 5)]{0x1}; + for (int i = 1; i < lim; ++i) { + for (int j = 0; j < n; ++j) { + if (!(vis[(cur ^ (1 << j)) >> 5] & (1 << ((cur ^ (1 << j)) & 0x1F)))) { + ret.push_back(cur ^= (1 << j)); + vis[cur >> 5] |= (1 << (cur & 0x1F)); + break; + } + } + } + delete[] vis; + return ret; + } +}; + +class Solution0ms { +public: + static std::vector grayCode(int n) { + std::vector ans = {0, 1}; + for (int i = 2; i <= n; i++) { + int x = (1 << (i - 1)); + int idx = ans.size() - 1; + while (idx >= 0) { + int num = (ans[idx] + x); + ans.push_back(num); + idx--; + } + } + return ans; + } +}; + +int main() { + const int n = 30; + auto t1 = std::chrono::high_resolution_clock::now(); + SolutionOld::grayCode(n); + auto t2 = std::chrono::high_resolution_clock::now(); + Solution::grayCode(n); + auto t4 = std::chrono::high_resolution_clock::now(); + Solution0ms::grayCode(n); + auto t5 = std::chrono::high_resolution_clock::now(); + std::cout << "SolutionOld: " << std::chrono::duration_cast(t2 - t1).count() << "ms" << std::endl; + std::cout << "Solution: " << std::chrono::duration_cast(t4 - t2).count() << "ms" << std::endl; + std::cout << "Solution0ms: " << std::chrono::duration_cast(t5 - t4).count() << "ms" << std::endl; + return 0; +} diff --git a/2201/CMakeLists.txt b/2201/CMakeLists.txt index 9bcff76..98932c2 100644 --- a/2201/CMakeLists.txt +++ b/2201/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2201) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2201 220107.cpp) \ No newline at end of file +ADD_EXECUTABLE(2201 220108-CN.cpp) \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f3c99c..533e154 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,6 +3,7 @@ PROJECT(LeetCodeDaily) SET(CMAKE_CXX_STANDARD 23) +# -Ofast -march=native -mtune=native -finline-functions -ffast-math -fomit-frame-pointer SET(CMAKE_CXX_FLAGS "-Wall") ADD_EXECUTABLE(LeetCodeDaily main.cpp)