洛谷 [P2216] 理想的正方形
2024-09-30 06:25:43
二维单调队列
先横向跑一边单调队列,记录下每一行长度为n的区间的最值
在纵向跑一边单调队列,得出结果
注意,mi要初始化为一个足够大的数
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
int init() {
int rv = 0, fh = 1;
char c = getchar();
while(c < '0' || c > '9') {
if(c == '-') fh = -1;
c = getchar();
}
while(c >= '0' && c <='9') {
rv = (rv<<1) + (rv<<3) + c - '0';
c = getchar();
}
return fh * rv;
}
const int MAXN = 2005;
int num[MAXN][MAXN], ma[MAXN][MAXN], mi[MAXN][MAXN], n, a, b, ans = 0x7fffffff;
struct ddque{
int que[MAXN<<3], head, tail;
void clear(bool opt){
que[0] = opt? 0: 0x7fffffff; //注意这里
head = tail = 0;
}
void insert(int x, bool opt){
if(!opt) {
while(que[tail] > x && tail >= head) tail--;
que[++tail] = x;
}else {
while(que[tail] < x && tail >= head) tail--;
que[++tail] = x;
}
}
void pop(int x){
if(que[head] == x) head++;
}
int query(){
return que[head];
}
}q1, q2;
int main() {
freopen("in.txt", "r", stdin);
memset(mi,0x7f,sizeof(mi));
a = init(); b = init(); n = init();
for(int i = 1 ; i <= a ; i++) {
for(int j = 1 ; j <=b ; j++) {
num[i][j] = init();
}
}
for(int i = 1 ; i <= a ; i++) {
q1.clear(0); q2.clear(1);
for(int j = 1 ; j <= n ; j++) {
q1.insert(num[i][j], 0);
q2.insert(num[i][j], 1);
}
ma[i][n] = q2.query();
mi[i][n] = q1.query();
for(int j = n + 1 ; j <= b ; j++) {
q1.insert(num[i][j], 0);
q2.insert(num[i][j], 1);
q1.pop(num[i][j - n]);
q2.pop(num[i][j - n]);
ma[i][j] = q2.query();
mi[i][j] = q1.query();
}
}
for(int j = n ; j <= b ; j++) {
q1.clear(0); q2.clear(1);
for(int i = 1 ; i <= n ; i++) {
q1.insert(mi[i][j], 0);
q2.insert(ma[i][j], 1);
}
ans = min(ans, q2.query() - q1.query());
for(int i = n + 1 ; i <= a ; i++) {
q1.insert(mi[i][j], 0);
q2.insert(ma[i][j], 1);
q1.pop(mi[i - n][j]);
q2.pop(ma[i - n][j]);
ans = min(ans, q2.query() - q1.query());
}
}
cout<<ans<<endl;
fclose(stdin);
return 0;
}
最新文章
- join Linq
- @Transient注解----Hiberbate
- IE里面的一些BUG记录
- PHP内核研究(内存管理1)
- svn利用钩子实现代码同步到web目录
- ionic本质
- [.NET] 使用C#开发SQL Function来提供服务 - 简讯发送
- An overview of the Spring MVC request flow
- (正则表达式应用) 替换自闭合标签(self-closing tag)的method
- frame模型
- 【百度地图API】多家地图API文件大小对比
- javascript1
- django文件上传
- linux iio子系统
- RabbitMQ (三) 发布/订阅
- C++_调用约束
- 性能监控扩展篇(grafana + influxdb + telegraf)
- java BASE64流 输出图片。
- LeetCode144:Binary Tree Preorder Traversal
- 2017 MoveIt!更新 ros indigo