二维树状数组基本操作

单点修改区间查询

LOJ #133. 二维树状数组 1:单点修改,区间查询

根据二维前缀和的思想对普通树状数组优化:

const int N = 4106;

inline ll Read()
{
	ll x = 0, f = 1;
	char c = getchar();
	while (c != '-' && (c < '0' || c > '9')) c = getchar();
	if (c == '-') f = -f, c = getchar();
	while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar();
	return x * f;
}

int n, m;
ll t[N][N];

void modify(int x, int y, ll val)
{
	for (int i = x; i <= n; i += i & -i)
		for (int j = y; j <= m; j += j & -j)
			t[i][j] += val;
}

ll query(int x, int y)
{
	ll ans = 0;
	for (int i = x; i; i -= i & -i)
		for (int j = y; j; j -= j & -j)
			ans += t[i][j];
	return ans;
}

int main()
{
	n = Read(), m = Read(); 
	for (int op, a, b, c, d; scanf ("%d", &op) != EOF; )
	{
		if(op == 2) a = Read(), b = Read(), c = Read(), d = Read(), 
			printf ("%lld\n", query(c, d) - query(a - 1, d) - query(c, b - 1) + query(a - 1, b - 1));
		else a = Read(), b = Read(), c = Read(), modify(a, b, c);
	}
	return 0;
}

单点修改区间查询

LOJ #135. 二维树状数组 3:区间修改,区间查询

一般区间修改的树状数组维护的都是差分数组,那么二维的也应该维护二维差分数组,接着是求和:

\[\begin{aligned}&\sum_{x=1}^{a}\sum_{y=1}^{b}\sum_{i=1}^{x}\sum_{j=1}^{y}t_{i,j}\\ =&\sum_{i=1}^{a}\sum_{j=1}^{b}(a-i+1)(b-j+1)t_{i,j}\\ =&(a+1)(b+1)\sum_{i=1}^{a}\sum_{j=1}^{b}t_{i,j}-\\ &(b+1)\sum_{i=1}^{a}\sum_{j=1}^{b}t_{i,j}\cdot i-\\ &(a+1)\sum_{i=1}^{a}\sum_{j=1}^{b}t_{i,j}\cdot j+\\ &\sum_{i=1}^{a}\sum_{j=1}^{b}t_{i,j}\cdot ij\end{aligned}\]

const int N = 4106;

inline ll Read()
{
	ll x = 0, f = 1;
	char c = getchar();
	while (c != '-' && (c < '0' || c > '9')) c = getchar();
	if (c == '-') f = -f, c = getchar();
	while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar();
	return x * f;
}

int n, m;
ll t[4][N][N];

void modify(int x, int y, ll val)
{
	for (int i = x; i <= n; i += i & -i)
		for (int j = y; j <= m; j += j & -j)
			t[0][i][j] += val,
			t[1][i][j] += val * x,
			t[2][i][j] += val * y,
			t[3][i][j] += val * x * y;
}

ll query(int x, int y)
{
	ll ans = 0;
	for (int i = x; i; i -= i & -i)
		for (int j = y; j; j -= j & -j)
			ans += (x + 1) * (y + 1) * t[0][i][j] - 
			       (y + 1) * t[1][i][j] -
				   (x + 1) * t[2][i][j] + 
				   t[3][i][j];
	return ans;
}

int main()
{
	n = Read(), m = Read(); 
	for (int op, a, b, c, d, k; scanf ("%d", &op) != EOF; )
	{
		if(op == 2) a = Read(), b = Read(), c = Read(), d = Read(), 
			printf ("%lld\n", query(c, d) - query(a - 1, d) - query(c, b - 1) + query(a - 1, b - 1));
		else a = Read(), b = Read(), c = Read(), d = Read(), k = Read(), 
			modify(a, b, k), modify(a, d + 1, -k), modify(c + 1, b, -k), modify(c + 1, d + 1, k);
	}
	return 0;
}
posted @ 2021-06-11 19:48  Jayun  阅读(42)  评论(0编辑  收藏  举报