應用背景:
我們對單調隊列的需求是基本不變的,即準系統上沒有什麼特殊的需求,主要改動都是在幾個地方:隊列中儲存的下標格式(如數字,元組等)、每個下標對應的值、對值大小的比較、下標之前的距離(用於剔除超過範圍的下標) 解決方案:
1.對於不變的單調隊列,寫了一個struct Q,對於不同的需求不需要改動,可以重用
2.對於上述的幾個需求,都可以對下邊的Node結構進行定義來實現 補充:
可以一定程度上減少重複代碼,而且並沒有使用虛函數什麼的,因為只是單純的從減少代碼量方面來考慮。以後如果有更好的方法,隨時更新。
///Node用來表示一個下標,存放到單調隊列中(需要修改)struct Node { int row, col; Node(int row = 0, int col = 0) { this->row = row; this->col = col; } ///返回下標對應的值(需要修改) int getValue() { return mat[row][col]; } ///x是否比y好,下標對應的值的比較(需要修改) bool betterThan(Node& y) { return getValue() > y.getValue(); } ///計算兩個節點的下標距離,下標的比較(需要修改) int getDistWith(Node& y) { return abs(col - y.col); }};template <typename T>struct Q { T index[maxn]; int l, r; void init() { l = 0; r = -1; } void add(T idx) { while (r >= l && idx.betterThan(index[r])) r--; index[++r] = idx; } T getFirst() { if (l <= r) return index[l]; else return NULL; } void trim(int maxDiff) { T maxIdx = index[r]; while (l <= r && maxIdx.getDistWith(index[l]) >= maxDiff) l++; }};