Example 1
Input
11
NEW A 3 4
NEW B 3 4
SET A 0 1 5
SET A 2 3 7
SET B 0 1 -2
SET B 1 0 4
ADD C A B
GET C 0 1
GET C 1 0
NNZ C
MUL D A BOutput
3
4
3
ERRORImplement SparseMatrix, which represents a matrix that stores only non-zero values and supports efficient matrix operations.
This problem focuses on data structure design and algorithmic efficiency, not linear algebra tricks.
SparseMatrix(rows, cols)rows is the number of rows in the matrix.cols is the number of columns in the matrix.set(r, c, val)(r, c) to val.val == 0, the entry must be removed from storage if present.0 ≤ r < rows and 0 ≤ c < cols.get(r, c)(r, c).0.add(other)SparseMatrix equal to this + other.multiply(other)SparseMatrix equal to this * other.this.cols == other.rows.nnz()The first line contains an integer Q, the number of operations.
Each of the next Q lines is one of the following:
NEW name rows cols
Create a new sparse matrix with the given name.
SET name r c val
Call set(r, c, val) on matrix name.
GET name r c
Call get(r, c) and output the result.
ADD out A B
Compute A + B and store the result in out.
MUL out A B
Compute A * B and store the result in out.
NNZ name
Call nnz() and output the result.
You may assume:
GET operation, output a single integer.NNZ operation, output a single integer.ADD or MUL operations, output ERROR.1 ≤ rows, cols ≤ 2000002 * 10^511
NEW A 3 4
NEW B 3 4
SET A 0 1 5
SET A 2 3 7
SET B 0 1 -2
SET B 1 0 4
ADD C A B
GET C 0 1
GET C 1 0
NNZ C
MUL D A B3
4
3
ERROR6
NEW A 3 3
SET A 0 0 5
SET A 1 2 7
GET A 0 0
GET A 2 2
NNZ A5
0
2