AcWing 单调队列优化DP 1091. 理想的正方形

import sys
sys.stdin = open('data.txt', 'r')

'''
先按照行求每行每一个滑动窗口中的最大值和最小值
然后再纵向求每一列的滑动窗口最大最小值,然后统计
每一个最大值最小值二元组的差值的最小值即可
'''


from collections import deque

m, n, k = map(int, input().split())
arr = []
for i in range(m):
    arr.append( list(map(int, input().split())) )


def get_window(s, width):
    ans = []
    que1, que2 = deque(), deque()

    for i, val in enumerate(s):
        while len(que1) > 0 and i - que1[0][0] >= width:
            que1.popleft()
        while len(que1) > 0 and val >= que1[-1][1]:
            que1.pop()
        que1.append((i, val))

        while len(que2) > 0 and i - que2[0][0] >= width:
            que2.popleft()
        while len(que2) > 0 and val <= que2[-1][1]:
            que2.pop()
        que2.append((i, val))

        if i >= width-1:
            ans.append( (que2[0][1], que1[0][1]) )
    return ans


def get_min_max_window(s, width):
    ans = []
    que1, que2 = deque(), deque()

    for i, (min_val, max_val) in enumerate(s):
        while len(que1) > 0 and i - que1[0][0] >= width:
            que1.popleft()
        while len(que1) > 0 and max_val >= que1[-1][1]:
            que1.pop()
        que1.append((i, max_val))

        while len(que2) > 0 and i - que2[0][0] >= width:
            que2.popleft()
        while len(que2) > 0 and min_val <= que2[-1][1]:
            que2.pop()
        que2.append((i, min_val))

        if i >= width - 1:
            ans.append((que2[0][1], que1[0][1]))
    return ans

arr1 = []
for i in range(m):
    arr1.append(get_window(arr[i], k))

ans = 0x7fffffff
for j in range(n-k+1):
    line = get_min_max_window([arr1[i][j] for i in range(m)], k)
    for min_val, max_val in line:
        ans = min(ans, max_val - min_val)

print(ans)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值