Matrix from Arrays——前缀和

Matrix from Arrays

时间限制: 1 Sec  内存限制: 128 MB
提交: 21  解决: 7
[提交] [状态] [讨论版] [命题人:admin]

题目描述

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.

输入

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).

输出

For each test case, print an integer representing the sum over the specific sub matrix for each query.

样例输入

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

样例输出

1
101
1068
2238
33076541

思路:对于奇数以L*L为一个循环,但为偶数时则不然,是以2L*2L为循环的;我们直接以2*l为循环节

#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll a[11];
ll b[100][100];
ll n;
ll nb(ll x,ll y)
{
if(x<0||y<0) return 0;
 
    return b[n-1][n-1]*(x/n)*(y/n)+b[x%n][n-1]*(y/n)+b[n-1][y%n]*(x/n)+b[x%n][y%n];
 
}
 
 
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
 
        cin>>n;
        ll i,j;
        for(i=0; i<n; i++)
            scanf("%lld",&a[i]);
        ll cursor = 0;
        for ( i = 0; i<=45; ++i)  //填充我们的矩阵
        {
            for ( j = 0; j <= i; ++j)
            {
                b[j][i - j] = a[cursor];
                cursor = (cursor + 1) % n;
            }
        }
        n=2*n;
         for( i=0;i<n;i++)//计算循环矩阵的二维前缀和
        {
            for( j=0;j<n;j++)
            {
                if(i) b[i][j]+=b[i-1][j];
                if(j) b[i][j]+=b[i][j-1];
                if(i&&j) b[i][j]-=b[i-1][j-1];
            }
        }
 
        ll q;
        scanf("%lld",&q);
        while(q--)
        {ll x0,y0,x,y;
        scanf("%lld %lld %lld %lld",&x0,&y0,&x,&y);
        int l1,l2;
 
 
 
     printf("%lld\n",nb(x,y)-nb(x,y0-1)-nb(x0-1,y)+nb(x0-1,y0-1));
 
    }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wearegamer/article/details/81663657