content: update content
All checks were successful
Build and Deploy Quartz / build-and-deploy (push) Has been skipped

This commit is contained in:
2026-01-11 18:15:22 +08:00
parent 8ee00c8767
commit db3a26f53b
3 changed files with 209 additions and 350 deletions

View File

@@ -0,0 +1,52 @@
Official docs about [Phantom Type & Data](https://doc.rust-lang.org/rust-by-example/generics/phantom/testcase_units.html)
# Example
```rust
#![allow(unused)]
use std::marker::PhantomData;
use std::fmt::{Display, Formatter, Result};
use std::any::type_name;
enum Sec {}
enum Min {}
struct Duration<Unit> {
value: i32,
unit: PhantomData<Unit>,
}
impl<U> Duration<U> {
fn new(value: i32) -> Duration<U> {
Duration {
value: value,
unit: PhantomData
}
}
}
impl<U> Display for Duration<U> {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(
f,
"{} {}",
self.value, type_name::<U>(),
)
}
}
fn print_second(sec: Duration<Sec>) {
println!("Printed: {}", sec);
}
fn main() {
// ok, rust compiler will imply that
// Duration::new(1) is with unit sec
print_second(Duration::new(1));
let duration_min = Duration::<Min>::new(10);
// compile time error! type mismatch
// print_second(duration_min);
}
```

9
rust_code/test.rs Normal file
View File

@@ -0,0 +1,9 @@
use std::io;
fn main() {
let mut test = 1;
}
fn call_function<CbFunc: Fn(i32)>(func: CbFunc, data: i32) {
func(data);
}

462
test.cpp
View File

@@ -1,373 +1,183 @@
#include <algorithm> // https://leetcode.com/problems/last-day-where-you-can-still-cross
#include <format>
#include <iostream> #include <iostream>
#include <numeric> #include <format>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <vector> #include <vector>
using std::cout, std::endl; using std::cout, std::endl;
using std::format; using std::format;
using std::vector, std::string; using std::vector;
bool debug = false; const bool debug = true;
/** class UnionFind2D
* Data structure to store pattern in question {
private: // private class
class UnionFindNode
{
public:
// record the rank of this node
int rank = 0;
// row, col work together as the parent pointer of this node
short row = 0;
short col = 0;
// special metadata for this node
bool valid = false;
bool top = false;
bool bottom = false;
bool isRoot()
{
return valid && (col == 0);
}
// merge this node to another node
// need to provide parent and its position
// will skip if parent is not valid
void mergeTo(UnionFindNode &parent, short r, short c)
{
// validate
if (!isRoot() || !parent.isRoot())
{
return;
}
// update pointer, pointing to parent
row = r;
col = c;
// update parent rank
parent.rank += rank;
// update parent metadata
if (top)
{
parent.top = 1;
}
if (bottom)
{
parent.bottom = 1;
}
}
};
private: // private variables
// mCount * mCount represents the total size
int mCount = 0;
UnionFindNode mNodes[20010][20010];
private: // private methods
/**
* Get root node of a position
* *
* Init: * Return invalid node if original node invalid,
* - Use 3-char string to init (based on questoni definition) * else, return root node
* - Use three different char parameter to init
*
* Method:
* - Equal comparator
* - hash() function
*/ */
struct Pattern UnionFindNode &getRoot(short r1, short c1)
{
char top;
char left;
char right;
// 123123
Pattern(const string &data)
{ {
top = data[2]; UnionFindNode &curNode = mNodes[r1][c1];
left = data[0];
right = data[1]; if (!curNode.valid)
{
return curNode;
} }
Pattern(char top, char left, char right) while (!curNode.isRoot())
: top(top), left(left), right(right) {}
bool operator==(const Pattern &other) const
{ {
return top == other.top && left == other.left && right == other.right; curNode = mNodes[curNode.row][curNode.col];
} }
size_t hash() const return curNode;
{
return std::hash<char>()(top) + std::hash<char>()(left) +
std::hash<char>()(right);
}
};
struct PatternHash
{
size_t operator()(const Pattern &p) const { return p.hash(); }
};
class PatternManager
{
private:
std::unordered_set<Pattern, PatternHash> mPatterns;
bool mPairs[6][6];
public:
PatternManager()
{
clear();
} }
void add(const Pattern &p) // if an idx is valid as a position pointer
bool validRange(short idx)
{ {
mPatterns.insert(p); if (idx < 1 || idx > mCount)
mPairs[p.left - 'A'][p.right - 'A'] = 1;
}
bool exists(const Pattern &p)
{
if (!mPairs[p.left - 'A'][p.right - 'A'])
{ {
return false; return false;
} }
return mPatterns.find(p) != mPatterns.end();
}
void clear()
{
mPatterns.clear();
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
mPairs[i][j] = 0;
}
}
}
};
// global variables
// 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;
class AnswerCache
{
private:
std::unordered_map<string, bool> mAllowedBottomcache;
unsigned long long cacheHit, cacheWrite, cacheRead;
private:
string wholeRowToString(unsigned rowIdx)
{
string s = "";
for (int i = 0; i <= rowIdx; ++i)
{
s.push_back(pyramid[rowIdx][i]);
}
return s;
}
public:
AnswerCache() {}
void setCache()
{
mAllowedBottomcache[wholeRowToString(curR)] = false;
}
// false: not in cache, true: hit
int getCache(int rowIdx)
{
++cacheRead;
string rowStr = wholeRowToString(rowIdx);
return mAllowedBottomcache.contains(rowStr);
}
void showCacheStatus()
{
cout << format("cache R/W: {}/{}, cache hit:{}\n", cacheRead, cacheWrite, cacheHit);
}
void clear()
{
mAllowedBottomcache.clear();
cacheHit = 0;
cacheRead = 0;
cacheWrite = 0;
}
};
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();
// clear answer cache
ansCache.clear();
// 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; return true;
} }
// backward
else /**
* Connect r1, c1 to r2, c2
* Ignore if one of those are not exists
*/
void connect(short r1, short c1, short r2, short c2)
{ {
if (curC >= bottomSize - 2 && curR >= bottomSize - 2) // validate range
bool allValid = validRange(r1) && validRange(c1) && validRange(r2) && validRange(c2);
if (!allValid)
{ {
return false; return;
} }
if (curC < curR) // get nodes
UnionFindNode &n1 = getRoot(r1, c1);
UnionFindNode &n2 = getRoot(r2, c2);
// merge nodes
if (n1.rank > n2.rank)
{ {
++curC; n2.mergeTo(n1, r1, c1);
} }
else else
{ {
++curR; n1.mergeTo(n2, r2, c2);
curC = 0;
}
return true;
} }
} }
char &curChar() { return pyramid[curR][curC]; } public: // public method
UnionFind2D(int count) : mCount(count)
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())); clear(count);
} }
void setToNextPossibleChar() /**
* Mark a position as land, then connect it to other land block around if exists
* Note: r, c should be 1-indexed
*/
void add(int r, int c)
{ {
bool firstMove = (curChar() == '0'); UnionFindNode &curNode = mNodes[r][c];
// search end // create new node and init data if not added before (invalid)
if (curChar() == '1') if (!curNode.valid)
{ {
return; curNode.valid = 1;
curNode.rank = 1;
if (r == 1)
{
curNode.top = 1;
} }
if (r == mCount)
// search not begin
if (curChar() == '0')
{ {
curChar() = 'A'; curNode.bottom = 1;
if (curValid())
{
return;
} }
} }
++curChar(); // connect to nodes around
connect(r, c, r, c + 1);
while (curChar() <= 'F' && !curValid()) connect(r, c, r, c - 1);
{ connect(r, c, r + 1, c);
++curChar(); connect(r, c, r - 1, c);
} }
if (curChar() > 'F') void clear(int mCount)
{ {
curChar() = '1'; mCount = mCount;
}
}
void _search() // note: better init method?
for (int i = 0; i < mCount; ++i)
{ {
if (debug) for (int j = 0; j < mCount; ++j)
{ {
cout << "enter _search()" << endl; mNodes[i][j] = UnionFindNode();
}
// already found answer
if (found || finished)
{
cout << "found or finished" << endl;
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;
// this position finished
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
isDelta = deltaSearchpointer(1);
if (!isDelta)
{
found = 1;
}
else
{
curChar() = '0';
}
return;
}
public:
void search()
{
while (!found && !finished)
{
_search();
if (debug)
{
cout << format("found={}, finished={}\n", found, finished);
} }
} }
} }
@@ -376,19 +186,7 @@ public:
class Solution class Solution
{ {
public: public:
bool pyramidTransition(string bottom, vector<string> &allowed) int latestDayToCross(int row, int col, vector<vector<int>> &cells)
{ {
// initialization
bottomSize = bottom.size();
auto initer = Initializer();
initer.initVariables();
initer.initPyramidBottom(bottom);
initer.initPattern(allowed);
// search the answer
auto searcher = Searcher();
searcher.search();
ansCache.showCacheStatus();
return found;
} }
}; };