数据结构:二维单调队列模板

模板:
二维单调队列维护二维区间最大值、最小值

点击查看折叠代码块
/*
二维单调队列可以维护区间的最大值,最小值
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long int LL;
const int MAXN = 1000 + 10;
const int INF = 0x3f3f3f3f;
int n, m, k, num[MAXN][MAXN], minNum[MAXN][MAXN], maxNum[MAXN][MAXN];
void solve(int type, int seg[][MAXN]){
    deque<pair<int, int> > deq;
    for (int i = 1; i <= n; i++){ //求行子段的最值。
        deq.clear();
        for (int j = 1; j <= m; j++){
            while (!deq.empty() && j - deq.front().second >= k){ deq.pop_front(); }
            if (type){
                while (!deq.empty() && deq.back().first < num[i][j]){ deq.pop_back(); }
            }
            else{
                while (!deq.empty() && deq.back().first > num[i][j]){ deq.pop_back(); }
            }
            deq.push_back(make_pair(num[i][j], j));
            seg[i][j] = deq.front().first;
        }
    }
    for (int j = 1; j <= m; j++){ //求列的最值
        deq.clear();
        for (int i = 1; i <= n; i++){
            while (!deq.empty() && i - deq.front().second >= k){ deq.pop_front(); }
            if (type){
                while (!deq.empty() && deq.back().first < seg[i][j]){ deq.pop_back(); }
            }
            else{
                while (!deq.empty() && deq.back().first > seg[i][j]){ deq.pop_back(); }
            }
            deq.push_back(make_pair(seg[i][j], i));
            seg[i][j] = deq.front().first;
        }
    }
}
int main(){
    while (~scanf("%d%d%d", &n, &m, &k)){
        for (int i = 1; i <= n; i++){
            for (int j = 1; j <= m; j++){
                scanf("%d", &num[i][j]);
            }
        }
        int ans = INF;
        solve(0, minNum); solve(1, maxNum);//求区间最小值,最大值
        for (int i = k; i <= n; i++){
            for (int j = k; j <= m; j++){
                ans = min(ans, maxNum[i][j] - minNum[i][j]);
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}
posted @ 2020-07-28 20:18  wsl_lld  阅读(100)  评论(0编辑  收藏  举报