滑窗模板_双向队列
附上电科算法讲堂 https://www.bilibili.com/video/av23189029?t=641 (感谢那些讲课的美好的人们)
/* * 注: 还有少许细节问题可能需要注意: 例如 总长度小于窗口长度的情况. * 和rGetMax rGetMin 下标小于零的情况 没有pass.. */ class HuaChuang_Max { public: struct cnobe { int id; int val; cnobe () {} cnobe (int _id, int _val) : id(_id), val(_val) {} }; deque<cnobe> cq; int GetMax(int date[], int ans[], int sz, int len) { // [a, b] a>=1 开始滑窗 int cnt = 0; int i; while (!cq.empty()) cq.pop_back(); for (i=1; i<len; ++i) { while (!cq.empty() && cq.back().val < date[i]) cq.pop_back(); cq.push_back(cnobe(i, date[i])); } for (i=len; i<=sz; ++i) { while (!cq.empty() && cq.back().val < date[i]) cq.pop_back(); cq.push_back(cnobe(i, date[i])); while (i - cq.front().id >= len) cq.pop_front(); ans[cnt++] = cq.front().val; } return cnt; } int GetMin(int date[], int ans[], int sz, int len) { // [a, b] a>=1 开始滑窗 int cnt = 0; int i; while (!cq.empty()) cq.pop_back(); for (i=1; i<len; ++i) { while (!cq.empty() && cq.back().val > date[i]) cq.pop_back(); cq.push_back(cnobe(i, date[i])); } for (i=len; i<=sz; ++i) { while (!cq.empty() && cq.back().val > date[i]) cq.pop_back(); cq.push_back(cnobe(i, date[i])); while (i - cq.front().id >= len) cq.pop_front(); ans[cnt++] = cq.front().val; } return cnt; } int rGetMax(int date[], int ans[], int sz, int len) { // [a, b] a>=1 开始滑窗 int cnt = 0; int i; while (!cq.empty()) cq.pop_back(); for (i=sz; i>sz-len+2 && i>0; --i) { while (!cq.empty() && cq.back().val < date[i]) cq.pop_back(); cq.push_back(cnobe(i, date[i])); } for (i=sz-len+2; i>0; --i) { while (!cq.empty() && cq.back().val < date[i]) cq.pop_back(); cq.push_back(cnobe(i, date[i])); while (cq.front().id - i >= len) cq.pop_front(); ans[i] = cq.front().val; cnt++; } return cnt; } int rGetMin(int date[], int ans[], int sz, int len) { // [a, b] a>=1 开始滑窗 int cnt = 0; int i; while (!cq.empty()) cq.pop_back(); for (i=sz; i>sz-len+2 && i>0; --i) { while (!cq.empty() && cq.back().val > date[i]) cq.pop_back(); cq.push_back(cnobe(i, date[i])); } for (i=sz-len+2; i>0; --i) { while (!cq.empty() && cq.back().val > date[i]) cq.pop_back(); cq.push_back(cnobe(i, date[i])); while (cq.front().id - i >= len) cq.pop_front(); ans[i] = cq.front().val; cnt++; } return cnt; } }hc;