Maps app~40 min2s · 256 MBtarget O((N + q) log rows log cols) time, O(rows × cols) spaceclassic twin: lc-308fenwick-tree
A map service divides a city into a grid of cells. Each cell holds the number of ride requests waiting in it. Requests arrive and are cancelled all day, so a cell's count goes up and down.
A dispatcher often asks about a block of cells: how many requests are waiting in this rectangle of the city? Your team lead asks: "Answer every such question while the counts keep changing."
Write block_totals(grid, ops).
grid is the starting counts: grid[r][c] is the count in row r and column c. Every row has the same length.ops is the list of operations, in order. Each is [kind, a, b, c, d].kind is 0, add c to the cell at row a and column b. The change c may be negative, and d is 0.kind is 1, ask for the total of the cells from row a to row c and from column b to column d, all included.Input: grid = [[3, 0, 1], [4, 1, 0], [1, 2, 5]], ops = [[1, 0, 0, 2, 2], [0, 1, 1, 4, 0], [1, 1, 1, 2, 2], [1, 0, 0, 1, 1]]
Output: [17, 12, 12]Each question uses the counts at that moment. The whole grid starts with 17 requests. The update puts 4 more in the middle cell, so the lower right block has 12 requests in total.
| Operation | Effect | Answer |
|---|---|---|
| total of rows 0 to 2, columns 0 to 2 | block of 9 cells | 17 |
| add 4 to row 1, column 1 | cells change | - |
| total of rows 1 to 2, columns 1 to 2 | block of 4 cells | 12 |
| total of rows 0 to 1, columns 0 to 1 | block of 4 cells | 12 |
Input: grid = [[2]], ops = [[1, 0, 0, 0, 0]]
Output: [2]A grid of one cell with one question returns that cell's count.
Input: grid = [[1, 2, 3]], ops = [[1, 0, 1, 0, 2], [0, 0, 1, 5, 0], [1, 0, 1, 0, 1]]
Output: [5, 7]A block can be a single row or column. Here the second question covers a single cell after the first changes it.
1 ≤ rows, cols ≤ 1280 ≤ grid[r][c] ≤ 1,000,0000 ≤ len(ops) ≤ 30,001, and every operation has exactly 5 numbers.a ≤ c and b ≤ d for a question.Adding up the cells of a block costs up to 16,384 steps for each question, and there can be 15,000 questions, so about 138,240,000 steps. A grid of 128 by 128 has 8 levels of binary blocks in each direction. A two-level tree of block totals answers a question with 4 corner totals and applies an update, each in about 64 steps.