Problem E. Matrix from Arrays
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 649 Accepted Submission(s): 289
Problem Description
Kazari has an array A length of L, she plans to generate an infinite matrix M using A.
The procedure is given below in C/C++:
int cursor = 0;for (int i = 0; ; ++i) { for (int j = 0; j <= i; ++j) { M[j][i - j] = A[cursor]; cursor = (cursor + 1) % L; } } Her friends don't believe that she has the ability to generate such a huge matrix, so they come up with a lot of queries about M, each of which focus the sum over some sub matrix. Kazari hates to spend time on these boring queries. She asks you, an excellent coder, to help her solve these queries.
Input
The first line of the input contains an integer T (1≤T≤100) denoting the number of test cases.
Each test case starts with an integer L (1≤L≤10) denoting the length of A.
The second line contains L integers A0,A1,...,AL−1 (1≤Ai≤100).
The third line contains an integer Q (1≤Q≤100) denoting the number of queries.
Each of next Q lines consists of four integers x0,y0,x1,y1 (0≤x0≤x1≤108,0≤y0≤y1≤108) querying the sum over the sub matrix whose upper-leftmost cell is (x0,y0) and lower-rightest cell is (x1,y1).Output
For each test case, print an integer representing the sum over the specific sub matrix for each query.
Sample Input
1
3
1 10 100
5
3 3 3 3
2 3 3 3
2 3 5 8
5 1 10 10
9 99 999 1000
Sample Output
1
101
1068
2238
33076541
Source
题意:
给了你一个可以通过一个数组无限构造矩阵的函数,然后通过构造出来的矩阵,求子矩阵和。
即题目中的程序构造一个新的矩阵,询问q次,问以(x1,y1)为左上角,(x2,y2)为右下角的矩阵内的元素之和(原点在左上角)。
题解:
构造的矩阵有循环结,我们通过打表可以发现这个大矩阵都是以左上角2l*2l的小矩阵M循环出现的,所以对于每次查询我们只需统计他要查询的矩阵包含多少个完整的M,对于那些不构成完整的行列和,我们首先用前缀和统计出来,最后加起来即可。我的方法用下图表示,答案就是S1-S2-S3+S4(S4为左上角那个小正方形):
下图是L=4,A[]={1,2,3,4}的矩阵的一部分。
以下解答转于http://tokitsukaze.live/
红色矩阵都是一样的。
假设我们要求蓝色矩阵的和。
蓝色矩阵的和=6个1号矩阵+3个2号矩阵+2个3号矩阵+1个4号矩阵。
所以做法就是预处理一下2L*2L矩阵的二维前缀和。然后每次这么算一下就行了,结合图和代码理解一下。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int A[10],M[400][400];
int L;
ll calc(int n,int m) {
if(n < 0 || m < 0) return 0;
return 1LL * M[L - 1][L - 1] * (n / L) * (m / L) + \
1LL * M[n % L][L - 1] * (m / L) + \
1LL * M[L - 1][m % L] * (n / L) + \
1LL * M[n % L][m % L];
}
void solve() {
scanf("%d",&L);
for(int i = 0; i < L ; i++) {
scanf("%d",&A[i]);
}
int cursor = 0;
for (int i = 0; i < 4 * L; ++i) {
for (int j = 0; j <= i; ++j) {
if(j < 2 * L && i - j < 2 * L)
M[j][i - j] = A[cursor];
cursor = (cursor + 1) % L;
}
}
L *= 2;
for(int i = 0; i < L;i++){
for(int j = 0;j < L;j++){
if(i) M[i][j] += M[i - 1][j];
if(j) M[i][j] += M[i][j - 1];
if(i&&j) M[i][j] -= M[i-1][j-1];
}
}
int p;
int x1,y1,x2,y2;
for(cin >>p;p;p--){
cin >> x1 >> y1 >> x2 >> y2;
cout << calc(x2,y2) - calc(x1 - 1, y2) - calc(x2, y1 - 1) + calc(x1 - 1, y1 - 1) << endl;
}
}
int main() {
int _;
for(cin>>_; _; _--) {
solve();
}
}