CP: Paint the grid

A wall is a grid of R rows and C columns, all painted 0 times. You paint k rectangles; each rectangle adds 1 to every cell inside it. Print how many times each cell was painted.

What to build

Use a 2D difference array. For a rectangle from (r1, c1) to (r2, c2) do d[r1][c1]++, d[r1][c2 + 1]--, d[r2 + 1][c1]-- and d[r2 + 1][c2 + 1]++. Then take running sums along every row and then down every column.

Requirements

  • Each rectangle costs O(1) to record
  • Positions are 1-based
  • Print the grid, one row per line, values separated by spaces

Input

The first line has R, C and k. Each of the next k lines has r1 c1 r2 c2.

Output

R lines of C numbers.

Constraints

1 ≤ R, C ≤ 100. 1 ≤ k ≤ 10,000. 1 ≤ r1 ≤ r2 ≤ R and 1 ≤ c1 ≤ c2 ≤ C.

Example

Input:

3 4 2
1 1 2 2
2 2 3 4

Output:

1 1 0 0 
1 2 1 1 
0 1 1 1 

Why it works

The four corner marks make the row-wise and then column-wise running sums add 1 exactly inside the rectangle: the first sum spreads the mark along the row, the second along the column, and the negative marks cancel it outside. Each rectangle costs O(1) instead of O(R × C).

Examples

Example 1 · Input
3 4 2
1 1 2 2
2 2 3 4
Expected output
1 1 0 0 
1 2 1 1 
0 1 1 1 
Example 2 · Input
2 2 1
1 1 2 2
Expected output
1 1 
1 1 

Hints

Hint 1

Make d with R + 2 rows and C + 2 columns so the index r2 + 1 and c2 + 1 are valid.

Hint 2

Rebuild: for each row, d[i][j] += d[i][j - 1]; then for each column, d[i][j] += d[i - 1][j].

Hint 3

Print only rows 1 to R and columns 1 to C.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int R, C, k;
    cin >> R >> C >> k;
    vector<vector<int> > d(R + 2, vector<int>(C + 2, 0));
    for (int i = 0; i < k; i++) {
        int r1, c1, r2, c2;
        cin >> r1 >> c1 >> r2 >> c2;
        d[r1][c1]++;
        d[r1][c2 + 1]--;
        d[r2 + 1][c1]--;
        d[r2 + 1][c2 + 1]++;
    }
    for (int i = 1; i <= R; i++)
        for (int j = 1; j <= C; j++) d[i][j] += d[i][j - 1];
    for (int i = 1; i <= R; i++)
        for (int j = 1; j <= C; j++) d[i][j] += d[i - 1][j];
    for (int i = 1; i <= R; i++) {
        for (int j = 1; j <= C; j++) cout << d[i][j] << " ";
        cout << "\n";
    }
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Difference arrays →