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)

猜你喜欢

转载自blog.csdn.net/xiaohaowudi/article/details/107751385