http://poj.org/problem?id=1195
求矩阵和的时候,下标弄错WA了一次...
求矩形(x1,y1) (x2,y2)的sum
|sum=sum(x2,y2)-sum(x1-1,y2)-sum(x2,y1-1)+sum(x1-1,y1-1)
二维树状数组讲解:http://blog.csdn.net/u011026968/article/details/38532117
二维树状数组模板:
/*==================================================*
| 二维树状数组
| 1、初始化:INIT: c[][]置为0; Row,Col要赋初值
| 数组下标一定要从1开始!!!!!!!!!
| 2、sum(i,j) 前i行前j列的和,update(i,j,num)
| 将(i,j)加上num
| 3、求矩形(x1,y1) (x2,y2)的sum
|sum=sum(x2,y2)-sum(x1-1,y2)-sum(x2,y1-1)+sum(x1-1,y1-1)
|注意Sum和c 必要的时候用long long
*==================================================*/
const int N = 10000;
int c[N][N]; int Row, Col;
inline int Lowbit(const int &x){// x > 0
return x&(-x);
}
int Sum(int i,int j){
int tempj, sum = 0;
while( i > 0 ){
tempj= j;
while( tempj > 0 ){
sum += c[i][tempj];
tempj -= Lowbit(tempj);
}
i -= Lowbit(i);
}
return sum;
}
void Update(int i, int j, int num){
int tempj;
while( i <= Row ){
tempj = j;
while( tempj <= Col ){
c[i][tempj] += num;
tempj += Lowbit(tempj);
}
i += Lowbit(i);
}
}
poj 1195 代码
#include
#include
#include
#include
#include
#include
#include