13.Maximal Sum
http://acm.fzu.edu.cn/problem.php?pid=1018
直接进行枚举的效果非常不好,需改进
是否是一维的最大子数组的变体
import sys
import numpy as np
def maximal_sum(matrix:'ndarray',N):
max_sum=-float('inf')
for h in range(0,N):
for l in range(0,N):
for w in range(0,N):
for step_h in range(1,N+1):
for step_l in range(1,N+1):
for step_w in range(1,N+1):
if h+step_h<=N and l+step_l<=N and w+step_w<=N:
sub_matrix=matrix[h:h+step_h,l:l+step_l,w:w+step_w]
temp=sub_matrix.sum()
if temp>max_sum:
max_sum=temp
print(max_sum)
lines=sys.stdin.readlines()
if lines and int(lines[0].rstrip())!=0:
line_left=0 # 某一个用例中剩余未被读取的行数
for line in lines:
if line_left==0:
N=int(line.rstrip)
if axis==0:
break
line_left=N**2
numbers=[]
else:
numbers.extend([int(x) for x in line.rstrip().split(' ')])
line_left-=1
if line_left==0:
matrix=np.array(numbers)
matrix.shape=(N,N,N)
maximal_sum(matrix,N)
# 法二 问题转换——降维处理
# 只对函数部分代码进行更改
import numpy as np
def maximal_sum_ndm3(matrix,N:'层'):
max_sum=-float('inf')
for i in range(0,N):
for j in range(i+1,N+1):
sub_matrix=matrix[i:j,:,:].sum(axis=0)
s=maximal_sum_ndm2(sub_matrix,N)
if s>max_sum:
max_sum=s
print(max_sum)
def maximal_sum_ndm2(matrix,N:'行'):
max_sum=-float('inf')
for i in range(0,N):
for j in range(i+1,N+1):
sub_matrix=matrix[i:j,:].sum(axis=0)
s=maximal_sum_ndm1(sub_matrix,N)
if s>max_sum:
max_sum=s
return max_sum
def maximal_sum_ndm1(matrix,N:'列'):
mid=N//2
if mid==0:
return matrix[0]
l_matrix=matrix[:mid]
r_matrix=matrix[mid:]
l_max_sum=maximal_sum_ndm1(l_matrix,mid)
r_max_sum=maximal_sum_ndm1(r_matrix,N-mid)
mid_l_sum=-float('inf')
mid_r_sum=-float('inf')
for i in range(0,mid+1):
s=matrix[i:mid+1].sum()
if s>mid_l_sum:
mid_l_sum=s
for i in range(mid+2,N+1):
s=matrix[mid+1:i].sum()
if s>mid_r_sum:
mid_r_sum=s
mid_max_sum=mid_l_sum+mid_r_sum
msum_array=np.array([l_max_sum,r_max_sum,mid_max_sum])
return int(msum_array.max())
if __name__=='__main__':
N=10
matrix=np.array([x for x in range(0,N**3)])
#matrix=np.array([0,-1,3,-5,7,4,-8,9,1,-1,-3,-1,2,-1,5,0,-1,3,3,1,-1,1,3,2,1,-2,1])
matrix.shape=(N,N,N)
maximal_sum_ndm3(matrix,N)
print(matrix)