POJ 1195 Mobile phones(二维树状数组)

转载请注明出处忆梦http://blog.csdn.net/yimeng2013/article/details/14229173


题目链接:http://poj.org/problem?id=1195

类型 :二维数组的 单点修改,区间查询  

题目大意:有一个S*S的矩阵,有以下操作:
                    0  S  表示初始化一个S*S的矩阵,矩阵中每个元素被初始化为0
                    1   X Y A  表示将c[X][Y] 增加A
                   2   L B R T 表示求出c[X][Y]的和,其中 L<=X<=R  B<=Y<=T
                    3   结束

#include<cstdio>
#include<cstring>
#define N 1030
#define LL long long
int c[N][N];
int n;

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

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

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

}


int main ()
{
	int op;
	scanf("%d %d", &op, &n);
	{
		
		while(scanf("%d",&op) && op != 3 )
		{
			int x1,y1,x2,y2,d;
			if(op == 1)
			{
				scanf("%d %d %d", &x1, &y1, &d);
				x1++,y1++;
				add(x1,y1,d);
			}
			else if(op == 2)
			{
				scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
				x1++, x2++, y1++, y2++;
				LL ans = 0;
				ans += sum(x2, y2);
				ans -= sum(x1-1, y2);
				ans -= sum(x2, y1-1);
				ans += sum(x1-1, y1-1);
				printf("%lld\n", ans);
			}
		}
	}
	return 0;
}


你可能感兴趣的:(树状数组)