diff --git a/test.cpp b/test.cpp index 1dfc048..b6bc5bf 100644 --- a/test.cpp +++ b/test.cpp @@ -126,38 +126,16 @@ private: public: AnswerCache() {} - // using the curR and curC, this method will work out the - // bottom string of the sub-pyramid that use such index as top element - // then set the cache for that bottom sequence - void setCache(bool state, bool onlySetWhenNotExists = false) + void setCache() { - // deal with each layer from curR to the bottom - for (unsigned workingRow = curR + 1; workingRow < bottomSize; ++workingRow) - { - // figure out the target string that need to be cache for this layer - string workingStr = wholeRowToString(workingRow); - string subStr = workingStr.substr(curR, workingRow - curR + 1); - - if (onlySetWhenNotExists && mAllowedBottomcache.contains(subStr)) - { - return; - } - mAllowedBottomcache[subStr] = state; - } + mAllowedBottomcache[wholeRowToString(curR)] = false; } - // 0: false, 1: true, -1:not cached + // false: not in cache, true: hit int getCache(int rowIdx) { string rowStr = wholeRowToString(rowIdx); - if (mAllowedBottomcache.contains(rowStr)) - { - return mAllowedBottomcache[rowStr]; - } - else - { - return -1; - } + return mAllowedBottomcache.contains(rowStr); } void clear() @@ -289,7 +267,6 @@ private: curChar() = 'A'; if (curValid()) { - ansCache.setCache(true); return; } } @@ -304,11 +281,6 @@ private: if (curChar() > 'F') { curChar() = '1'; - ansCache.setCache(false, true); - } - else - { - ansCache.setCache(true); } } @@ -321,6 +293,17 @@ private: return; } + // try use cache to check if we could skip current layer + // before we are about to start a new upper layer + if (curC == curR && curChar() == '0') + { + if (ansCache.getCache(curR + 1)) + { + deltaSearchpointer(0); + return; + } + } + setToNextPossibleChar(); bool isDelta; @@ -329,41 +312,33 @@ private: if (curChar() == '1') { isDelta = deltaSearchpointer(0); + + // finished if (!isDelta) { finished = 1; } + + // back to lower layer + if (curC == 0) + { + // remember this layer of pattern doesn't work + ansCache.setCache(); + } return; } // this position not finish searching - - // try use cache for next layer if this position is a start of new layer - if (curC == 0 && curChar() == '0') - { - bool cacheRes = ansCache.getCache(curR + 1); - if (cacheRes == 1) - { - found = true; - return; - } - else if (cacheRes == 0) - { - deltaSearchpointer(0); - return; - } - } - isDelta = deltaSearchpointer(1); if (!isDelta) { found = 1; - return; } else { curChar() = '0'; } + return; } public: