二维单调队列
在处理二维的单调队列问题的时候
先将每行做一遍单调队列
再对每列做一遍单调队列,就能实现二维的单调队列
CF1195E OpenStreetMap
题意
给出一个矩阵和a,b
计算所有大小为a*b的子矩阵的最小值
分析
由于子矩阵的大小是固定的
我们可以直接用二维单调队列维护子矩阵的最小值
先对每行做单调队列
再对每列做单调队列
代码
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#pragma warning (disable:4996)
typedef long long LL;
const int maxn = 3005;
int a[maxn][maxn];
int n, m, r, c, g, x, y, z;
void Pre_Work() {
scanf("%d%d%d%d", &n, &m, &r, &c);
scanf("%d%d%d%d", &g, &x, &y, &z);
for (int i = 1; i <= n; i++) {
a[i][1] = g;
for (int j = 2; j <= m; j++)
a[i][j] = (LL(a[i][j - 1]) * x + y) % z;
g = (LL(a[i][m]) * x + y) % z;
}
}
int q[maxn], b[maxn][maxn];
void R_Queue(int i) {
int head = 1, tail = 0;
for (int j = 1; j < c; j++) {
while (tail >= head && a[i][q[tail]] >= a[i][j]) tail--;
q[++tail] = j;
}
for (int j = c; j <= m; j++) {
while (tail >= head && a[i][q[tail]] >= a[i][j]) tail--;
q[++tail] = j;
while (tail >= head && q[head] < j - c + 1)head++;
b[i][j] = a[i][q[head]];
}
}
void C_Queue(int j) {
int head = 1, tail = 0;
for (int i = 1; i < r; i++) {
while (tail >= head && b[q[tail]][j] >= b[i][j])tail--;
q[++tail] = i;
}
for (int i = r; i <= n; i++) {
while (tail >= head && b[q[tail]][j] >= b[i][j]) tail--;
q[++tail] = i;
while (tail >= head && q[head] < i - r + 1)head++;
a[i][j] = b[q[head]][j];
}
}
int main() {
Pre_Work();
for (int i = 1; i <= n; i++)
R_Queue(i);
for (int i = c; i <= m; i++)
C_Queue(i);
LL ans = 0;
for (int i = r; i <= n; i++)
for (int j = c; j <= m; j++)
ans += a[i][j];
printf("%I64d\n", ans);
}