为了做一条题 poj 1195 Mobile phones 学的二维树状数组
这个人写得不错:
知识点链接:http://www.java3z.com/cwbwebhome/article/article1/1369.html?id=4804
人家写的 java 改头换面版,呵呵,挺神奇的~~~~
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 const int maxn = 100 + 10; 7 int A[maxn][maxn]; 8 int C[maxn][maxn]; 9 int row, col; 10 char query[15]; 11 12 int lowbit(int x) 13 { 14 return x & (-x); 15 } 16 17 int Sum(int i, int j) 18 { 19 int result = 0; 20 for (int x = i; x > 0; x -= lowbit(x)) 21 { 22 for (int y = j; y > 0; y -= lowbit(y)) 23 result += C[x][y]; 24 } 25 return result; 26 } 27 28 void Modify(int i, int j, int delta) 29 { 30 A[i][j] += delta; 31 32 for (int x = i; x < row; x += lowbit(x)) 33 { 34 for (int y = j; y < col; y += lowbit(y)) 35 C[x][y] += delta; 36 } 37 } 38 39 int main() 40 { 41 int tmp, x, y, ask, num; 42 while (1) 43 { 44 memset(A, 0, sizeof(A)); 45 memset(C, 0, sizeof(C)); 46 47 printf("请输入行和列: "); 48 scanf("%d%d", &row, &col); 49 for (int i = 1; i < row; i++) 50 { 51 for (int j = 1; j < col; j++) 52 { 53 scanf("%d", &tmp); 54 Modify(i, j, tmp); 55 } 56 } 57 printf("请输入查询的次数: "); 58 scanf("%d", &ask); 59 while (ask--) 60 { 61 scanf("%s", query); 62 if (query[0] == 'Q') 63 { 64 scanf("%d%d", &x, &y); 65 printf("%d ", Sum(x, y)); // 求子二维数组的和 66 } 67 else if (query[0] == 'M') 68 { 69 scanf("%d%d%d", &x, &y, &num); 70 Modify(x, y, num); // 将 A[x][y] 加 num 71 } 72 } 73 } 74 return 0; 75 }
特别要注意:行和列都是从1开始的!!! 所以输入的 5 行 5 列 实质是 4 * 4 的矩阵