poj1195Mobile phones 二维树状数组

c[i,j]=∑a[x,y](i-lowbit(i)<x<=i,j-lowbit(j)<y<=j);

一维的树状数组是一段一段的和,二维的树状是一个一个子矩阵的和,sum(x, y)求得矩阵(1, 1)到(x, y)的和。

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
#define N 1026
int S[N][N];
int n;

int lowbit(int x) {
	return x & (-x);
}

int add(int i, int x, int m) {
	while(x <= n) {
		S[i][x] += m;
		x += lowbit(x);
	}
}

int sum(int i, int end) {
	int result = 0;
	while(end > 0) {
		result += S[i][end];
		end -= lowbit(end);
	}
	return result;
}
void print() {
	for (int i = 1; i<= n; i++) {
		for (int j = 1; j <= n; j++)
			cout<<S[i][j]<<' ';
		cout<<endl;
	}	
}


int main() {
	int op, x, y, a, l, b, r, t;
	memset(S, 0, sizeof(S));
	while(scanf("%d", &op) && op != 3) {
		if (op == 0) {
			scanf("%d", &n);
			continue;
		}
		else if (op == 1) {
			scanf("%d %d %d", &x, &y, &a);
			add(x+1, y+1, a);
			//print();
		}
		else if (op == 2) {
			scanf("%d %d %d %d", &l, &b, &r, &t);
			int ans = 0;
			for (int i = l+1; i <= r+1; i++)
				ans += (sum(i, t+1) - sum(i, b));
			printf("%d\n", ans);
		}
	}
	return 0;
}


你可能感兴趣的:(poj1195Mobile phones 二维树状数组)