code: cache using lower triangle
This commit is contained in:
588
test.cpp
588
test.cpp
@@ -1,294 +1,396 @@
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <numeric>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <unordered_map>
|
||||
#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;
|
||||
|
||||
struct TaskInfo
|
||||
/**
|
||||
* Data structure to store pattern in question
|
||||
*
|
||||
* Init:
|
||||
* - Use 3-char string to init (based on questoni definition)
|
||||
* - Use three different char parameter to init
|
||||
*
|
||||
* Method:
|
||||
* - Equal comparator
|
||||
* - hash() function
|
||||
*/
|
||||
struct Pattern
|
||||
{
|
||||
unsigned start = 0;
|
||||
unsigned end = 0;
|
||||
char top;
|
||||
char left;
|
||||
char right;
|
||||
|
||||
TaskInfo(const vector<int> &vec) : start(vec[0]), end(vec[1]) {}
|
||||
|
||||
bool operator<(const TaskInfo &other)
|
||||
Pattern(const string &data)
|
||||
{
|
||||
if (start != other.start)
|
||||
{
|
||||
return start < other.start;
|
||||
}
|
||||
|
||||
return end < other.end;
|
||||
top = data[2];
|
||||
left = data[0];
|
||||
right = data[1];
|
||||
}
|
||||
|
||||
unsigned duration() const
|
||||
Pattern(char top, char left, char right)
|
||||
: top(top), left(left), right(right) {}
|
||||
|
||||
bool operator==(const Pattern &other) const
|
||||
{
|
||||
return end - start;
|
||||
return top == other.top && left == other.left && right == other.right;
|
||||
}
|
||||
|
||||
void delay(unsigned delta)
|
||||
size_t hash() const
|
||||
{
|
||||
start += delta;
|
||||
end += delta;
|
||||
}
|
||||
|
||||
void relocate(unsigned startTime)
|
||||
{
|
||||
end = startTime + duration();
|
||||
start = startTime;
|
||||
return std::hash<char>()(top) + std::hash<char>()(left) +
|
||||
std::hash<char>()(right);
|
||||
}
|
||||
};
|
||||
|
||||
class MeetingRoomManager
|
||||
struct PatternHash
|
||||
{
|
||||
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.
|
||||
*/
|
||||
unsigned use()
|
||||
{
|
||||
// room not found
|
||||
if (tmpUnusedIdxHeap.empty())
|
||||
{
|
||||
return 100;
|
||||
}
|
||||
|
||||
// found room with lowest index
|
||||
unsigned unuse = tmpUnusedIdxHeap.top();
|
||||
tmpUnusedIdxHeap.pop();
|
||||
|
||||
++mUseCount[unuse]; // update use count
|
||||
|
||||
// update most use if needed
|
||||
if (mUseCount[unuse] > tmpMostUsedCount)
|
||||
{
|
||||
tmpMostUsedCount = mUseCount[unuse];
|
||||
}
|
||||
|
||||
return unuse; // return room idx
|
||||
}
|
||||
|
||||
/**
|
||||
* Unuse a room by its index
|
||||
*/
|
||||
void unuse(unsigned roomIdx)
|
||||
{
|
||||
tmpUnusedIdxHeap.push(roomIdx);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
size_t operator()(const Pattern &p) const { return p.hash(); }
|
||||
};
|
||||
|
||||
class RoomDistributor
|
||||
class PatternManager
|
||||
{
|
||||
|
||||
private: // private classes
|
||||
struct FutureReleaseInfo
|
||||
{
|
||||
unsigned time;
|
||||
unsigned roomIdx;
|
||||
|
||||
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;
|
||||
}
|
||||
private:
|
||||
std::unordered_set<Pattern, PatternHash> mPatterns;
|
||||
bool mPairs[6][6];
|
||||
|
||||
public:
|
||||
RoomDistributor(unsigned roomCount) : mManager(roomCount) {}
|
||||
|
||||
// distribute a meeting task to the room
|
||||
void distributeTask(const TaskInfo &taskInfo)
|
||||
PatternManager()
|
||||
{
|
||||
pushTimeTo(taskInfo.start);
|
||||
clear();
|
||||
}
|
||||
|
||||
// if room still full, push timestamp until next room release
|
||||
if (mManager.isFull())
|
||||
void add(const Pattern &p)
|
||||
{
|
||||
mPatterns.insert(p);
|
||||
mPairs[p.left - 'A'][p.right - 'A'] = 1;
|
||||
}
|
||||
|
||||
bool exists(const Pattern &p)
|
||||
{
|
||||
if (!mPairs[p.left - 'A'][p.right - 'A'])
|
||||
{
|
||||
releaseOne();
|
||||
return false;
|
||||
}
|
||||
|
||||
// distribute a room
|
||||
unsigned roomIdx = mManager.use();
|
||||
// record a new future release
|
||||
mReleaseTimeHeap.emplace(FutureReleaseInfo(mCurTimestamp + taskInfo.duration(), roomIdx));
|
||||
return mPatterns.find(p) != mPatterns.end();
|
||||
}
|
||||
|
||||
/**
|
||||
* Release all item that should be released in the future
|
||||
*/
|
||||
void releaseAll()
|
||||
void clear()
|
||||
{
|
||||
while (!mReleaseTimeHeap.empty())
|
||||
mPatterns.clear();
|
||||
for (int i = 0; i < 6; ++i)
|
||||
{
|
||||
releaseOne();
|
||||
for (int j = 0; j < 6; ++j)
|
||||
{
|
||||
mPairs[i][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsigned getMostUsedIdx()
|
||||
{
|
||||
return mManager.mostUsedIdx();
|
||||
}
|
||||
|
||||
void clear(unsigned count)
|
||||
{
|
||||
// reset timestamp
|
||||
mCurTimestamp = 0;
|
||||
// clean heap
|
||||
releaseAll();
|
||||
// clear mManager
|
||||
mManager.clear(count);
|
||||
}
|
||||
};
|
||||
|
||||
// global variables
|
||||
unsigned roomCount, meetingCount;
|
||||
RoomDistributor distributor(0);
|
||||
vector<TaskInfo> tasks;
|
||||
// statistics
|
||||
unsigned bottomSize = 0;
|
||||
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
|
||||
tasks.clear();
|
||||
tasks.reserve(meetings.size());
|
||||
for (const auto &m : meetings)
|
||||
{
|
||||
tasks.emplace_back(TaskInfo(m));
|
||||
}
|
||||
std::sort(tasks.begin(), tasks.end());
|
||||
private:
|
||||
std::unordered_map<string, bool> mAllowedBottomcache;
|
||||
|
||||
// init distributor
|
||||
distributor.clear(roomCount);
|
||||
}
|
||||
|
||||
void triggerSimulation()
|
||||
{
|
||||
for (const auto &t : tasks)
|
||||
string wholeRowToString(unsigned rowIdx)
|
||||
{
|
||||
distributor.distributeTask(t);
|
||||
string s = "";
|
||||
for (int i = 0; i <= rowIdx; ++i)
|
||||
{
|
||||
s.push_back(pyramid[rowIdx][i]);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
distributor.releaseAll();
|
||||
}
|
||||
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
|
||||
{
|
||||
public:
|
||||
int mostBooked(int n, vector<vector<int>> &meetings)
|
||||
bool pyramidTransition(string bottom, vector<string> &allowed)
|
||||
{
|
||||
roomCount = n;
|
||||
meetingCount = meetings.size();
|
||||
// initialization
|
||||
bottomSize = bottom.size();
|
||||
auto initer = Initializer();
|
||||
initer.initVariables();
|
||||
initer.initPyramidBottom(bottom);
|
||||
initer.initPattern(allowed);
|
||||
|
||||
initVariables(meetings);
|
||||
triggerSimulation();
|
||||
|
||||
return distributor.getMostUsedIdx();
|
||||
// search the answer
|
||||
auto searcher = Searcher();
|
||||
searcher.search();
|
||||
return found;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user