Problem E. Matrix from Arrays
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1169 Accepted Submission(s): 526
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
2018 Multi-University Training Contest 4
题意:按照题目要求的方式对一个矩阵填数,Q个询问,给出一个子矩阵的左上角和右下角的坐标,输出这个子矩阵的和
思路:首先可以打表发现当L为奇数时,整个矩阵都是由L*L的子矩阵组成,当L为偶数时,整个矩阵都是由2L*2L的子矩阵构成,所以这个大矩阵是以2L*2L为周期的,然后利用二维前缀和和容斥思想求和
#include <stdio.h>
typedef long long ll;
const int MAXN = 2e2+5;
ll sum[MAXN][MAXN];
int A[MAXN];
int L;
ll calc(int x,int y)
{
ll res = 0;
res = sum[L - 1][L - 1] * (x / L) * (y / L);
res += sum[x % L][y % L];
res += (x / L) * sum[L - 1][y % L];
res += (y / L) * sum[x % L][L - 1];
return res;
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) {
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++) {
scanf("%d",&A[i]);
}
if(n&1) L = n * 2;
else L = n * 4;
int cur = 0;
for(int i = 0; i < L; i++) {
for(int j = 0; j <= i; j++) {
sum[j][i - j] = A[cur];
cur = (cur + 1) % n;
}
}
L /= 2;
for(int i = 0; i < L; i++) {
for(int j = 0; j < L; j++) {
sum[i][j] += sum[i][j - 1];
sum[i][j] += sum[i - 1][j];
sum[i][j] -= sum[i - 1][j - 1];
}
}
int q;
scanf("%d",&q);
while(q--) {
int x0,y0,x1,y1;
scanf("%d %d %d %d",&x0,&y0,&x1,&y1);
ll ans = calc(x1,y1) - calc(x0 - 1,y1) - calc(x1,y0 - 1) + calc(x0 - 1,y0 - 1);
printf("%lld\n",ans);
}
}
return 0;
}