题目描述
Given a matrix of size n×m and an integer k, where A i,j =lcm(i,j), the least common multiple of i and j. You should determine the sum of the maximums among all k×k submatrices.
输入描述:
Only one line containing three integers n,m,k (1≤n,m≤5000,1≤k≤min{n,m}).
输出描述:
Only one line containing one integer, denoting the answer.
示例1
输入
3 4 2
输出
38
说明
The given matrix is:
1 2 3 4
2 2 6 4
3 6 3 12
The maximums among all 2×2 submatrices are 2, 6, 6, 6, 6, 12 respectively, and their sum is 38.
题目大意
给定一个n* m的矩阵A,A(i,j)=lcm(i,j),求所有A中的所有k* k的子矩阵中元素最大值之和。
解题思路:
对每一行都求一遍maxSlidingWindow,并把结果保存在res数组中。总共有n行,每行是O(m)
然后对res的每一列求一遍maxSlidingWindow,因为每个window中的k个数分别是各k行的k列的最大值,即求得的就是k个数的最大值,总共有m列,每列是O(n)
最后的代码复杂度是O(nm)。
Python代码:
from collections import deque
def maxSlidingWindow(nums, k):
res = []
Q = deque()
for i in range(k):
while Q and nums[Q[-1]] <= nums[i]:
Q.pop()
Q.append(i)
res.append(nums[Q[0]])
for i in range(k, len(nums)):
while Q and nums[Q[-1]] <= nums[i]:
Q.pop()
Q.append(i)
if Q[0] <= i - k:
Q.popleft()
res.append(nums[Q[0]])
return res
def maxpooling(matrix, k):
ans = []
for i in range(len(matrix)):
ans.append(maxSlidingWindow(matrix[i], k))
matrix = list(zip(*ans))
ans = []
for i in range(len(matrix)):
ans.append(maxSlidingWindow(matrix[i], k))
matrix = list(zip(*ans))
res = []
for i in range(len(matrix)):
res.extend(matrix[i])
return sum(res)
nums = [[1, 2, 3, 4], [2, 2, 6, 4], [3, 6, 3, 12]]
k = 2
res = maxpooling(nums, k)
print(res)