KOPC12G - K12-Bored of Suffixes and Prefixes

You are given a matrix of size NxN containing only upper case letters. You have to perform two kinds of operations:

  • Replace operation is to replace a row or column of the matrix with the given string.
  • Count Operation returns the count of each letter in the required region.

The operations are given as:

  • 0 x y str → Replace y th row with string str, if x = 0 or update yth column with string str (top to bottom), if x = 1
  • 1 x1 y1 x2 y2 → Count the number of each latter in the rectangular region of the matrix where (x1, y1) is top-left point of the rectangle and (x2, y2) is the bottom-right point of the rectangle.

For every Count operation output the value of (1*number of A's + 2*number of B's + ... 26*number of Z's).

Input

The first line of the input file contains T which denotes the number of test cases.

The first line of each test case contains two integers N and q where N denotes size of the matrix and q denotes the number of queries. This is followed by NxN alphabetic matrix. The matrix is followed by q lines of queries, in the above given format.

T <= 10

N <= 500, Q <= 10000

0 <= x1 < N, 0 <= x2 < N, 0 <= y1 < N, 0 <= y2 < N

x1 <= x2, y1 <= y2

Warning: Huge I/O

Output

Print the output for each query line by line.

Example

Input:
1
4 3
ABCD
ABCD
ABCD
ABCD
1 0 0 3 3
0 0 2 PQRS
1 0 2 3 3

Output:
40
58

Added by:Radhakrishnan Venkataramani
Date:2012-01-31
Time limit:0.100s-1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Own

hide comments
2022-05-14 06:45:29
2D BIT and AC in 3 go.Make sure to reset bit array after every testcase :)
2021-08-17 10:54:42
i used 2D BIT it got AC

Last edit: 2021-08-17 10:54:53
2019-04-12 11:33:52
TLE using BIT in 2D grid. Please someone give idea.
2012-10-28 12:14:37 :D
Theoretically O(N*Q) could be optimal, if number updates is at least comparable with the number of queries. Then the test case size is O(N*N + N*Q) (in bytes).
2012-03-12 12:43:52 Xunie J
O(NQlogN) also will pass!

Last edit: 2012-03-12 12:44:40
2012-02-18 10:40:12 ~ adieus ~
O(NQ) will pass !
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.