PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000162. Tổng các hình chữ nhật (Matrix Summation)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tổng các hình chữ nhật (Matrix Summation)

Matrix Summation

Source: SPOJ

Version: Phuoc Hung OJ – the test-case count is removed; the END command is retained.

Problem Statement

An initially zero-filled N×NN\times N integer matrix has zero-based coordinates. Process commands in the given order:

  • SET x y v: assign the cell (x,y)(x,y) the value vv, replacing its previous value.
  • SUM x1 y1 x2 y2: output the sum of all cells in the inclusive rectangle x1≤x≤x2x1\le x\le x2, y1≤y≤y2y1\le y\le y2.
  • END: terminate the command sequence, without producing output.

A SET operation is an assignment, not an increment.

Input

The first line gives NN. Subsequent lines contain SET x y v, SUM x1 y1 x2 y2 or END. The final line is END.

Output

For each SUM command, print one integer on its own line; SET and END produce no output.

Subtasks

  • Subtask 1 (20 points): 1≤N≤81\le N\le 8; 1≤Q≤401\le Q\le 40 commands preceding END; −1000≤v≤1000-1000\le v\le1000; SET coordinates 0≤x,y<N0\le x,y<N; SUM bounds 0≤x1≤x2<N0\le x1\le x2<N and 0≤y1≤y2<N0\le y1\le y2<N; each SUM fits signed 32-bit.
  • Subtask 2 (30 points): 1≤N≤1001\le N\le 100; 1≤Q≤12001\le Q\le 1200 commands preceding END; −1000≤v≤1000-1000\le v\le1000; SET coordinates 0≤x,y<N0\le x,y<N; SUM bounds 0≤x1≤x2<N0\le x1\le x2<N and 0≤y1≤y2<N0\le y1\le y2<N; each SUM fits signed 32-bit.
  • Subtask 3 (50 points): 1≤N≤10241\le N\le 1024; 1≤Q≤500001\le Q\le 50000 commands preceding END; −1000≤v≤1000-1000\le v\le1000; SET coordinates 0≤x,y<N0\le x,y<N; SUM bounds 0≤x1≤x2<N0\le x1\le x2<N and 0≤y1≤y2<N0\le y1\le y2<N; each SUM fits signed 32-bit.

Examples

Example 1

Input

4
SET 0 0 1
SUM 0 0 3 3
SET 2 2 12
SUM 2 2 2 2
SUM 2 2 3 3
SUM 0 0 2 2
END

Output

1
12
12
13

Explanation

The matrix starts at zero. After setting (0,0) to 1 the whole-grid sum is 1. Setting (2,2) to 12 makes the next two rectangle sums equal 12. The final query contains both nonzero cells and returns 1+12=131+12=13.

Example 2

Input

3
SET 1 1 5
SUM 0 0 2 2
SET 1 1 2
SUM 0 0 2 2
SET 0 2 -3
SUM 0 1 1 2
END

Output

5
2
-1

Explanation

The second SET replaces 5 by 2; it does not add 2. The total changes from 5 to 2. After setting (0,2) to −3-3, the last queried rectangle contains −3-3 and 2 and totals −1-1.