█████████ ████ ███░░░░░███ ░░███ ███ ░░░ ██████ ███████ ██████ ██████ ░███ ███░░███ ███░░███ ███░░███ ███░░███ ░███ ░███ ░███░███ ░███ ░███████ ░███ ░███ ░░███ ███░███ ░███░███ ░███ ░███░░░ ░███ ░███ ░░█████████ ░░██████ ░░████████░░██████ ░░██████ ░░░░░░░░░ ░░░░░░ ░░░░░░░░ ░░░░░░ ░░░░░░

Envío 995

Problema 0xa6 - Submatriz de suma máxima en una matriz no muy grande

  • Autor: abatesins
  • Fecha: 2020-10-06 09:24:49 UTC (Hace más de 3 años)
Caso # Resultado Tiempo Memoria
#1
Correcto
0.024 s 3 KBi
#2
Correcto
0.025 s 3 KBi
#3
Correcto
0.026 s 3 KBi
#4
Correcto
0.026 s 3 KBi
#5
Correcto
0.024 s 3 KBi
#6
Correcto
0.022 s 3 KBi
#7
Correcto
0.028 s 3 KBi
#8
Tiempo límite excedido
0.25 s 3 KBi
#9
Tiempo límite excedido
0.161 s 3 KBi
#10
Tiempo límite excedido
0.174 s 7 KBi
#11
Tiempo límite excedido
0.176 s 3 KBi
#12
Tiempo límite excedido
0.159 s 3 KBi
#13
Tiempo límite excedido
0.183 s 3 KBi
#14
Tiempo límite excedido
0.156 s 3 KBi
#15
Tiempo límite excedido
0.194 s 3 KBi
#16
Tiempo límite excedido
0.16 s 3 KBi
#17
Tiempo límite excedido
0.199 s 3 KBi
#18
Tiempo límite excedido
0.172 s 3 KBi
Puntos totales: 39 / 100

Código

def get_integral_mat(mat):
    """
    Calculate integral matrix
    """
    nrows, ncols = len(mat), len(mat[0])
    sums_mat = [[0] * ncols for _ in range(nrows)]
    for i, row in enumerate(mat):
        for j, item in enumerate(row):
            ixy = mat[i][j]
            sx_1y = sums_mat[i][j-1] if j > 0 else 0
            sxy_1 = sums_mat[i-1][j] if i > 0 else 0
            sx_1y_1 = sums_mat[i-1][j-1] if i > 0 and j > 0 else 0
            sums_mat[i][j] = ixy + sx_1y + sxy_1 - sx_1y_1
    return sums_mat

def get_max_sum(mat):
    nrows, ncols = len(mat), len(mat[0])
    sums_mat = get_integral_mat(mat)
    max_sum = mat[0][0]
    for i in range(nrows):
        for j in range(ncols):
            for sub_i in range(i, nrows):
                for sub_j in range(j, ncols):
                    # calculate the sum using the integral matrix in O(1)
                    # doing s(a) - s(b) - s(c) + s(d) where a,b,c,d are the
                    # corners of the sub-matrix to be summed (in the original)
                    # matrix
                    s_a = sums_mat[i-1][j-1] if i > 0 and j > 0 else 0
                    s_b = sums_mat[i-1][sub_j] if i > 0 else 0
                    s_c = sums_mat[sub_i][j-1] if j > 0 else 0
                    s_d = sums_mat[sub_i][sub_j]
                    current_sum = s_a - s_b - s_c + s_d
                    if current_sum > max_sum:
                        max_sum = current_sum
    return max_sum

if __name__ == "__main__":
    nrows, ncols = list(map(int, input().split()))
    mat = [list(map(int, input().split())) for _ in range(nrows)]
    print(get_max_sum(mat))