二维树状数组--子矩阵求和

#include 
#define MAXN 1025

int c[MAXN][MAXN] = {0};
int a[MAXN][MAXN] = {0};

int lowbit(int n)
{
	return n & (n ^ (n - 1));
}


void add(int x, int y, int num, int n)
{
	for (int i = x; i <= n; i += lowbit(i))
	{
		for (int j = y; j <= n; j += lowbit(j))
		{
			c[i][j] += num;
		}
	}
}

int GetSum(int x, int y)
{
	int total = 0;
	for (int i = x; i > 0; i -= lowbit(i))
	{
		for (int j = y; j > 0; j -= lowbit(j))
		{
			total += c[i][j];
		}
	}
	return total;
}

int query(int x1, int y1, int x2, int y2)
{
	return GetSum(x2, y2) - GetSum(x1 - 1, y2) - GetSum(x2, y1 - 1) + GetSum(x1 - 1, y1 -1);
}

int main()
{
	int instruct = 0;
	int n = 0;
	scanf("%d %d", &instruct, &n);
	while (true)
	{
		scanf("%d", &instruct);
		int x1 = 0;
		int y1 = 0;
		int x2 = 0;
		int y2 = 0;
		int num = 0;
		if (1 == instruct)//指令为  将a[x1][y1] + num
		{
			scanf("%d %d %d", &x1, &y1, &num);
			add(x1 + 1, y1 + 1, num, n);
		}
		else if (2 == instruct)//指令为 求位于x1,y1到x2,y2的子矩阵的和
		{

			scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
			printf("%d\n", query(x1 + 1, y1 + 1, x2 + 1, y2 + 1));
		}
		else if(3 == instruct)//结束指令
		{
			break;
		}
	}
	return 0;
}

你可能感兴趣的:(算法代码)