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

Envío 1268

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

  • Autor: EstebanFS
  • Fecha: 2020-10-16 23:57:25 UTC (Hace alrededor de 4 años)
Caso # Resultado Tiempo Memoria
#1
Correcto
0.008 s 1 KBi
#2
Correcto
0.007 s 30 KBi
#3
Correcto
0.005 s 1 KBi
#4
Correcto
0.007 s 1 KBi
#5
Correcto
0.007 s 1 KBi
#6
Correcto
0.007 s 2 KBi
#7
Correcto
0.007 s 1 KBi
#8
Correcto
0.003 s 1 KBi
#9
Correcto
0.009 s 1 KBi
#10
Correcto
0.008 s 1 KBi
#11
Correcto
0.007 s 1 KBi
#12
Correcto
0.009 s 1 KBi
#13
Correcto
0.009 s 1 KBi
#14
Correcto
0.008 s 3 KBi
#15
Correcto
0.007 s 1 KBi
#16
Correcto
0.008 s 2 KBi
#17
Correcto
0.008 s 2 KBi
#18
Correcto
0.009 s 1 KBi
Puntos totales: 100 / 100

Código

#include <bits/stdc++.h>

using namespace std;


const int ROW = 105;
const int COL = 105;
int M[ROW][COL];
int arr[ROW];
int start, finish;
int n;

int kadane() {
  int sum = 0, maxSum = INT_MIN, i;
  finish = -1;
  int local_start = 0;
  for (i = 0; i < n; ++i) {
    sum += arr[i];
    if (sum < 0) {
      sum = 0;
      local_start = i + 1;
    }
    else if (sum > maxSum) {
      maxSum = sum;
      start = local_start;
      finish = i;
    }
  }
  if (finish != -1) return maxSum;
  // Special Case: When all numbers in arr are negative
  maxSum = arr[0];
  start = finish = 0;
  // Find the maximum element in array
  for (i = 1; i < n; i++) {
    if (arr[i] > maxSum) {
      maxSum = arr[i];
      start = finish = i;
    }
  }
  return maxSum;
}

void findMaxSum() {
  // Variables stato store the final output
  int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom; 
  int left, right, i;
  int sum;
  for (left = 0; left < COL; ++left) {
    memset(arr, 0, sizeof(arr));
    for (right = left; right < COL; ++right) {
      for (i = 0; i < ROW; ++i) arr[i] += M[i][right];
      sum = kadane();
      if (sum > maxSum) {
        maxSum = sum;
        finalLeft = left;
        finalRight = right;
        finalTop = start;
        finalBottom = finish;
      }
    }
  }
  cout << maxSum << endl;
}

int main() {
	int r, c, maxSingle = INT_MIN;
	cin >> r >> c;
	n = max(r, c);
	for(int i = 0; i < r; ++i) {
		for(int j = 0; j < c; ++j) {
			cin >> M[i][j];
			maxSingle = max(maxSingle, M[i][j]);
		}
	}
	if(maxSingle < 0) cout << maxSingle << endl;
	else findMaxSum();
	return 0;
}