Блог пользователя jha_gaurav98

Автор jha_gaurav98, история, 8 лет назад, По-английски

Given a square array of size N × N where each cell is filled with a number between  - 9 and 9. A sub square of size k is any set of k contiguous columns and k contiguous rows. For any sub square, the sum of elements in its cells is called a sub square sum. Given the N × N square, write a program to find the maximum sub square sum. (Note that a 1 × 1 square (k = 1) is not considered a sub square)

Constraints: 2 ≤ N ≤ 1000

By looking at the constraints I think we have to do it in O(N2). I could manage to reach to O(N3). Please Help

Thanks in advance

  • Проголосовать: нравится
  • +2
  • Проголосовать: не нравится

»
8 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by jha_gaurav98 (previous revision, new revision, compare).

»
8 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +9 Проголосовать: не нравится

Are you sure that N^3 isn't enough? The constant is quite low maybe if you use memory efficiently for cache it's enough?

»
8 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +1 Проголосовать: не нравится

I personally don't know any solution for this problem that is faster than O(N3). However, I think that you may be able to squeeze this solution under the time limit with the help of loop unrolling. Your code will look a little ugly. But it does wonders sometimes.

Generate 999 (because we don't consider 1x1 squares) switch cases in descending order. For each case, you fix a rectangle size and search the grid. Remember to remove break statements from the switch so that when N = X where 2 ≤ X ≤ 1000, then all squares of size X * X, (X - 1) * (X - 1), (X - 2) * (X - 2)... will be searched. You can easily get the sum of each candidate square in O(1) using inclusion-exclusion. So the total time-complexity is still O(N3). I am not sure how fast this approach would be. But this is the best that I can think of.