code: cache using lower triangle

This commit is contained in:
2025-12-31 01:04:43 +08:00
parent 31d1a1d95a
commit eac34bc0a7

584
test.cpp
View File

@@ -1,294 +1,396 @@
#include <algorithm>
#include <format>
#include <iostream> #include <iostream>
#include <numeric> #include <numeric>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <vector> #include <vector>
#include <format>
#include <algorithm>
#include <queue>
using std::cout, std::endl, std::format; using std::cout, std::endl;
using std::format;
using std::vector, std::string;
using std::vector, std::priority_queue; bool debug = false;
const bool debug = false; /**
* Data structure to store pattern in question
struct TaskInfo
{
unsigned start = 0;
unsigned end = 0;
TaskInfo(const vector<int> &vec) : start(vec[0]), end(vec[1]) {}
bool operator<(const TaskInfo &other)
{
if (start != other.start)
{
return start < other.start;
}
return end < other.end;
}
unsigned duration() const
{
return end - start;
}
void delay(unsigned delta)
{
start += delta;
end += delta;
}
void relocate(unsigned startTime)
{
end = startTime + duration();
start = startTime;
}
};
class MeetingRoomManager
{
private: // private member
vector<unsigned> mUseCount;
unsigned tmpMostUsedCount = 0;
std::priority_queue<unsigned, std::vector<unsigned>, std::greater<unsigned>> tmpUnusedIdxHeap;
public: // public member
// the count of the room
unsigned mCount = 0;
public: // public method
// initialize manager with room count
MeetingRoomManager(int count) : mCount(count)
{
mUseCount = vector<unsigned>(100);
clear(count);
}
/**
* Find a valid room, mark it as used and update the use count.
* Return index of the used room.
* *
* Return 100 if room not found. * Init:
* - Use 3-char string to init (based on questoni definition)
* - Use three different char parameter to init
*
* Method:
* - Equal comparator
* - hash() function
*/ */
unsigned use() struct Pattern
{
char top;
char left;
char right;
Pattern(const string &data)
{ {
// room not found top = data[2];
if (tmpUnusedIdxHeap.empty()) left = data[0];
{ right = data[1];
return 100;
} }
// found room with lowest index Pattern(char top, char left, char right)
unsigned unuse = tmpUnusedIdxHeap.top(); : top(top), left(left), right(right) {}
tmpUnusedIdxHeap.pop();
++mUseCount[unuse]; // update use count bool operator==(const Pattern &other) const
// update most use if needed
if (mUseCount[unuse] > tmpMostUsedCount)
{ {
tmpMostUsedCount = mUseCount[unuse]; return top == other.top && left == other.left && right == other.right;
} }
return unuse; // return room idx size_t hash() const
}
/**
* Unuse a room by its index
*/
void unuse(unsigned roomIdx)
{ {
tmpUnusedIdxHeap.push(roomIdx); return std::hash<char>()(top) + std::hash<char>()(left) +
} std::hash<char>()(right);
unsigned mostUsedIdx()
{
for (int i = 0; i < mCount; ++i)
{
if (mUseCount[i] == tmpMostUsedCount)
{
return i;
}
}
return 0;
}
bool isFull()
{
return tmpUnusedIdxHeap.empty();
}
void clear(unsigned count)
{
// reset mCount
mCount = count;
// clear most use count
tmpMostUsedCount = 0;
// clear use count statistics
std::fill(mUseCount.begin(), mUseCount.end(), false);
// init unuse heap
tmpUnusedIdxHeap = std::priority_queue<unsigned, std::vector<unsigned>, std::greater<unsigned>>();
for (int i = 0; i < mCount; ++i)
{
tmpUnusedIdxHeap.push(i);
}
} }
}; };
class RoomDistributor struct PatternHash
{ {
size_t operator()(const Pattern &p) const { return p.hash(); }
};
private: // private classes class PatternManager
struct FutureReleaseInfo {
{ private:
unsigned time; std::unordered_set<Pattern, PatternHash> mPatterns;
unsigned roomIdx; bool mPairs[6][6];
bool operator<(const FutureReleaseInfo &other) const
{
if (time != other.time)
{
return time > other.time;
}
return roomIdx > other.roomIdx;
}
};
private: // private members
// manage room usage info
MeetingRoomManager mManager;
// record current timestamp
unsigned mCurTimestamp = 0;
// record when to release room
std::priority_queue<FutureReleaseInfo> mReleaseTimeHeap;
private: // private methods
// release one from heap
// will NOT check empty before action!
void releaseOne()
{
const FutureReleaseInfo &nextReleaseInfo = mReleaseTimeHeap.top();
mManager.unuse(nextReleaseInfo.roomIdx);
mCurTimestamp = std::max({nextReleaseInfo.time, mCurTimestamp});
mReleaseTimeHeap.pop();
}
// release all the room until the given timestamp
void pushTimeTo(unsigned targetTime)
{
// already pushed to a time later then given, nothing to do
if (mCurTimestamp > targetTime)
{
return;
}
// no room is used, just move the time
if (mReleaseTimeHeap.empty())
{
mCurTimestamp = targetTime;
return;
}
// release until target time
while (!mReleaseTimeHeap.empty() && mReleaseTimeHeap.top().time <= targetTime)
{
releaseOne();
}
mCurTimestamp = targetTime;
}
public: public:
RoomDistributor(unsigned roomCount) : mManager(roomCount) {} PatternManager()
// distribute a meeting task to the room
void distributeTask(const TaskInfo &taskInfo)
{ {
pushTimeTo(taskInfo.start); clear();
// if room still full, push timestamp until next room release
if (mManager.isFull())
{
releaseOne();
} }
// distribute a room void add(const Pattern &p)
unsigned roomIdx = mManager.use(); {
// record a new future release mPatterns.insert(p);
mReleaseTimeHeap.emplace(FutureReleaseInfo(mCurTimestamp + taskInfo.duration(), roomIdx)); mPairs[p.left - 'A'][p.right - 'A'] = 1;
} }
/** bool exists(const Pattern &p)
* Release all item that should be released in the future
*/
void releaseAll()
{ {
while (!mReleaseTimeHeap.empty()) if (!mPairs[p.left - 'A'][p.right - 'A'])
{ {
releaseOne(); return false;
} }
return mPatterns.find(p) != mPatterns.end();
} }
unsigned getMostUsedIdx() void clear()
{ {
return mManager.mostUsedIdx(); mPatterns.clear();
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
mPairs[i][j] = 0;
}
} }
void clear(unsigned count)
{
// reset timestamp
mCurTimestamp = 0;
// clean heap
releaseAll();
// clear mManager
mManager.clear(count);
} }
}; };
// global variables // global variables
unsigned roomCount, meetingCount; // statistics
RoomDistributor distributor(0); unsigned bottomSize = 0;
vector<TaskInfo> tasks; string bottomString;
char pyramid[6][6]; // 0: not searched, A-F: searching, 1: finished
PatternManager pMgr;
// search temp
unsigned curR, curC;
bool found, finished;
void initVariables(const vector<vector<int>> &meetings) class AnswerCache
{ {
// init tasks private:
tasks.clear(); std::unordered_map<string, bool> mAllowedBottomcache;
tasks.reserve(meetings.size());
for (const auto &m : meetings)
{
tasks.emplace_back(TaskInfo(m));
}
std::sort(tasks.begin(), tasks.end());
// init distributor string wholeRowToString(unsigned rowIdx)
distributor.clear(roomCount);
}
void triggerSimulation()
{
for (const auto &t : tasks)
{ {
distributor.distributeTask(t); string s = "";
for (int i = 0; i <= rowIdx; ++i)
{
s.push_back(pyramid[rowIdx][i]);
} }
distributor.releaseAll(); return s;
} }
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)
{
// 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;
}
}
// 0: false, 1: true, -1:not cached
int getCache(int rowIdx)
{
string rowStr = wholeRowToString(rowIdx);
if (mAllowedBottomcache.contains(rowStr))
{
return mAllowedBottomcache[rowStr];
}
else
{
return -1;
}
}
void clear()
{
mAllowedBottomcache.clear();
}
};
AnswerCache ansCache;
class Initializer
{
public:
// init variables and clear mMgr
void initVariables()
{
// init temp
curR = bottomSize - 2;
curC = bottomSize - 2;
found = 0;
finished = 0;
// clear manager
pMgr.clear();
ansCache.clear();
// clear answer cache
// init pyramid
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
pyramid[i][j] = '0';
}
}
}
// init bottomString and the pyramid array
void initPyramidBottom(const string &data)
{
bottomString = data;
for (int i = 0; i < bottomSize; ++i)
{
pyramid[bottomSize - 1][i] = data[i];
}
}
// fill data to mMgr
void initPattern(const vector<string> &allowed)
{
for (const auto &s : allowed)
{
pMgr.add(Pattern(s));
}
}
};
class Searcher
{
private:
bool deltaSearchpointer(bool forward)
{
// forward
if (forward)
{
if (curR <= 0 && curC <= 0)
{
return false;
}
if (curC > 0)
{
--curC;
}
else
{
--curR;
curC = curR;
}
return true;
}
// backward
else
{
if (curC >= bottomSize - 2 && curR >= bottomSize - 2)
{
return false;
}
if (curC < curR)
{
++curC;
}
else
{
++curR;
curC = 0;
}
return true;
}
}
char &curChar() { return pyramid[curR][curC]; }
char &leftChar() { return pyramid[curR + 1][curC]; }
char &rightChar() { return pyramid[curR + 1][curC + 1]; }
bool atTop() { return curR == curC && curC == 0; }
bool curValid()
{
return pMgr.exists(Pattern(curChar(), leftChar(), rightChar()));
}
void setToNextPossibleChar()
{
// search end
if (curChar() == '1')
{
return;
}
// search not begin
if (curChar() == '0')
{
curChar() = 'A';
if (curValid())
{
ansCache.setCache(true);
return;
}
}
++curChar();
while (curChar() <= 'F' && !curValid())
{
++curChar();
}
if (curChar() > 'F')
{
curChar() = '1';
ansCache.setCache(false, true);
}
else
{
ansCache.setCache(true);
}
}
void _search()
{
// already found answer
if (found || finished)
{
return;
}
setToNextPossibleChar();
bool isDelta;
// this position finished
if (curChar() == '1')
{
isDelta = deltaSearchpointer(0);
if (!isDelta)
{
finished = 1;
}
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';
}
}
public:
void search()
{
while (!found && !finished)
{
_search();
}
}
};
class Solution class Solution
{ {
public: public:
int mostBooked(int n, vector<vector<int>> &meetings) bool pyramidTransition(string bottom, vector<string> &allowed)
{ {
roomCount = n; // initialization
meetingCount = meetings.size(); bottomSize = bottom.size();
auto initer = Initializer();
initer.initVariables();
initer.initPyramidBottom(bottom);
initer.initPattern(allowed);
initVariables(meetings); // search the answer
triggerSimulation(); auto searcher = Searcher();
searcher.search();
return distributor.getMostUsedIdx(); return found;
} }
}; };