Description
Here is a square matrix of n∗n, each lattice has its value (n must be odd), and the center value is n∗n. Its spiral decline along the center of the square matrix (the way of spiral decline is shown in the following figure:)
The grid in the lower left corner is (1,1) and the grid in the upper right corner is (n , n)
Now I can choose mm squares to build palaces, The beauty of each palace is equal to the digital sum of the value of the land which it is located. Such as (the land value is 123213,the beautiful values of the palace located on it is 1+2+3+2+1+3=12) (666 -> 18) (456 ->15)
Next, we ask pp times to the sum of the beautiful values of the palace in the matrix where the lower left grid(x1,y1), the upper right square (x2,y2).
Input
The first line has only one number T .Representing T-group of test data (T≤5)
The next line is three number: n m p
The mm lines follow, each line contains two integers the square of the palace (x,y)
The pp lines follow, each line contains four integers : the lower left grid(x1,y1) the upper right square(x2,y2)
Output
Next, p1+p2...+pT lines: Represent the answer in turn(n≤10^6)(m,p≤10^5)
Sample Input
1 3 4 4 1 1 2 2 3 3 2 3 1 1 1 1 2 2 3 3 1 1 3 3 1 2 2 3
Sample Output
5 18 23 17
Resume
回型填数,二维矩阵求和(无修改)。
Analysis
首先解决O(1)求取每个位置的数值:
如果令最外圈为第一圈,共有n/2圈加最中间单个元素。观察第x圈,共有 4*(n-x) 个数,其中每一边有n-x个元素(公用元素只属于其中一边)。
那么如果我们知道目标位置属于第几圈就可以求得该圈第一个元素标号。
可以发现,第x圈中的元素距离最近的边距离是x。
然后解决每一圈内,各个元素位置。按照 x=y 和 x=n+1-y 两条线划分出四个区域,恰好划分出四个边,分类讨论即可。
接下来解决求矩阵内元素和。
一看到这个问题,嗯,直接二维树状数组加离散化呗,板子题。TLE真香。看来N(logN)^2好像卡不过去嘞。
伟大的学长出现了,因此蒟蒻有机会学到这个新的算法:扫描线。
其实扫描线就是不断扫描的线段树。
考虑离线处理,询问区间和城堡都按照x坐标排序。维护一个线段树表示所有坐标小于x的城堡按照y轴的区间和。
x不断增大,依次处理以下三步:
- 将查询区间左端点为x的查询结果减去 y1 到 y2 的区间和;
- 用坐标为x的城堡数据更新y处线段树(加上城堡数值);
- 将查询区间右端点为x的查询结果加上 y1 到 y2 的区间和。
这便是扫描线的思路。
Code
待补充