http://www.spoj.com/problems/MATSUM/
MATSUM - Matrix Summation
A N × N matrix is filled with numbers. BuggyD is analyzing the matrix, and he wants the sum of certain submatrices every now and then, so he wants a system where he can get his results from a query. Also, the matrix is dynamic, and the value of any cell can be changed with a command in such a system.
Assume that initially, all the cells of the matrix are filled with 0. Design such a system for BuggyD. Read the input format for further details.
Input
The first line of the input contains an integer t, the number of test cases. t test cases follow.
The first line of each test case contains a single integer N (1 <= N <= 1024), denoting the size of the matrix.
A list of commands follows, which will be in one of the following three formats (quotes are for clarity):
- "SET x y num" - Set the value at cell (x, y) to num (0 <= x, y < N).
- "SUM x1 y1 x2 y2" - Find and print the sum of the values in the rectangle from (x1, y1) to (x2, y2), inclusive. You may assume that x1 <= x2 and y1 <= y2, and that the result will fit in a signed 32-bit integer.
- "END" - Indicates the end of the test case.
Output
For each test case, output one line for the answer to each "SUM" command. Print a blank line after each test case.
Example
Input: 1 4 SET 0 0 1 SUM 0 0 3 3 SET 2 2 12 SUM 2 2 2 2 SUM 2 2 3 3 SUM 0 0 2 2 END Output: 1 12 12 13
思路: 二维树状数组
分析:
1 简单的二维树状数组,注意因为数据量很大TLE了多次,之后把memset改成for循环A了
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 1100;
int n;
int mat[MAXN][MAXN];
int treeNum[MAXN][MAXN];
int lowbit(int x){
return x&(-x);
}
void add(int x , int y , int val){
for(int i = x ; i < MAXN ; i += lowbit(i))
for(int j = y ; j < MAXN ; j += lowbit(j))
treeNum[i][j] += val;
}
long long getSum(int x , int y){
long long ans = 0;
for(int i = x ; i > 0 ; i -= lowbit(i))
for(int j = y ; j > 0 ; j -= lowbit(j))
ans += treeNum[i][j];
return ans;
}
void solve(){
char str[10];
int x , y , val;
int x1 , y1 , x2 , y2;
while(scanf("%s" , str) && str[0] != 'E'){
if(str[1] == 'E'){
scanf("%d%d%d%*c" , &x , &y , &val);
add(x+1 , y+1 , val-mat[x+1][y+1]);
mat[x+1][y+1] = val;
}
else{
scanf("%d%d%d%d%*c" , &x1 , &y1 , &x2 , &y2);
x1++ , y1++ , x2++ , y2++;
long long ans = getSum(x2 , y2);
ans -= getSum(x1-1 , y2);
ans -= getSum(x2 , y1-1);
ans += getSum(x1-1 , y1-1);
printf("%lld\n" , ans);
}
}
}
int main(){
int cas;
scanf("%d" , &cas);
while(cas--){
scanf("%d%*c" , &n);
for(int i = 0 ; i <= n ; i++)
for(int j = 0 ; j <= n ; j++)
treeNum[i][j] = mat[i][j] = 0;
solve();
}
return 0;
}