树状数组(二叉索引树)

目录

一,树状数组

1,树状数组

2,区间更新单点查询

3,离散化

二,模板代码

三,OJ实战

CodeForces 706B Interesting drink

CSU 1770 按钮控制彩灯实验

HDU 1166 敌兵布阵

POJ 2309 BST

POJ 2352 HDU 1541 Stars

力扣 307. 区域和检索 - 数组可修改

力扣 2250. 统计包含每个点的矩形数目(离散化)

四,二维树状数组

1,模板代码

2,OJ实战

POJ 1195 Mobile phones

POJ 2155 Matrix (区间更新单点查询)

力扣 2536. 子矩阵元素加 1(区间更新单点查询)

五,支持在动态增长的数组中查询前缀最大值的树状数组


一,树状数组

1,树状数组

树状数组,也叫二叉索引树(Binary Indexed Tree)

如图,A是基本数组,C是求和数组,

其中,C[1]=A[1], C[2]=C[1]+A[2], C[3]=A[3], C[4]=C[2]+C[3]+A[4]......C[8]=C[4]+C[6]+C[7]+A[8]......

树状数组最简单最经典的使用场景,就是单点更新区间查询。

2,区间更新单点查询

对于一段区间内增加某个值的操作,可以利用差分,转换成单点更新,把单点更新,转换成前缀和查询。

3,离散化

参考离散化

二,模板代码

#include<iostream>
#include<string.h>
using namespace std;

template<int maxLen = 100000>
class TreeArray
{
public:
	TreeArray(int len)//len是元素实际数量,元素id范围是[1,n]
	{
		this->n = len;
		memset(c, 0, sizeof(int)*(len + 1));
	}
	void add(int i, int x)
	{
		while (i <= n)
		{
			c[i] += x;
			i += (i&(-i));
		}
	}
	int getSum(int i)
	{
		int s = 0;
		while (i)
		{
			s += c[i];
			i -= (i&(-i));
		}
		return s;
	}
private:
	int n;
	int c[maxLen+5];
};

三,OJ实战

CodeForces 706B Interesting drink

题目:

Description

Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.

Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink.

The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop.

The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink.

Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.

Output

Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.

Sample Input

Input
5
3 10 8 6 11
4
1
10
3
11
Output
0
4
1
5

这个题目就是,给出若干查询,对于每个查询,输出数组中有多少个数比它小。

这不就是最典型的树状数组吗?

代码:
 


#include <iostream>
#include <string.h>
using namespace std;



int main()
{
	int nn, a, q;
	scanf("%d", &nn);
	TreeArray<100000> opt(100000);
	for (int i = 0; i < nn; i++)
	{
		scanf("%d", &a);
		opt.add(a, 1);
	}
	scanf("%d", &q);
	for (int i = 0; i < q; i++)
	{
		scanf("%d", &a);
		if (a >= 100000)printf("%d\n", opt.getSum(100000));
		else printf("%d\n", opt.getSum(a));
	}
	return 0;
}

CSU 1770 按钮控制彩灯实验

题目:


Description

应教学安排,yy又去开心的做电学实验了。实验的内容分外的简单一串按钮通过编程了的EEPROM可以控制一串彩灯。然而选择了最low的一种一对一的控制模式,并很快按照实验指导书做完实验的yy马上感觉到十分无趣。于是他手指在一排按钮上无聊的滑来滑去,对应的彩灯也不断的变化着开关。已知每一个按钮按下会改变对应一个彩灯的状态,如此每次yy滑动都会改变一串彩灯的状态。现已知彩灯最初的状态,以及yy n次无聊的滑动的起点和终点l,r。现问彩灯最终的状态。

Input

有多组数据。
每组数据第一行,n(1<=n<=10^5)代表彩灯串长度,t(0<=t<=10^5)代表yy滑动的次数
第二行n个数(0表示灭1表示亮)给出n个彩灯的目前的状态。
之后t行每行两个数li,ri(1<=li<=ri<=n)代表每次滑动的区间。

Output

每组用一行输出最终的串的状态,格式见样例。

Sample Input

3 2
1 0 1
1 3
2 3
Sample Output

0 0 1

首先说下这个题目的思路。

肯定不能用暴力的θ(n*t)的方法。

很明显,这个题目是有规律的。

在区间左侧和区间右侧都没有被改变,只有区间中间的彩灯被改变了。

而且这个题目最后只需要判断奇偶性,所以彩灯被改变了多少次,就是直接等于有多少个区间端点在它的左侧。

例如,本题的2个区间是【1,3】【2,3】,

彩灯1的左侧有1个端点,彩灯2的左侧有2个端点,彩灯3的左侧有0个端点

注意!计算左侧的端点数量的时候,区间左端点刚好等于彩灯的情况是要算进去的,

但是区间右端点刚好等于彩灯的情况是不能算进去的。

再比如一个任意的例子,

8 1

0 0 0 0 0 0 0 0

3 6

很明显答案应该是0 0 1 1 1 1 0 0

要说这个例子找规律应该不难。第1、2个彩灯左边有0个区间端点,

第3、4、5、6个区间端点左边有1个端点,第7、8个彩灯左边有2个端点。

重复一遍:彩灯3计入了左端点3,彩灯6不计入右端点6。

其实还有一种思路:区间【3,6】这个操作可以分解成2个操作,

1,改变前6个彩灯的状态,2,改变前3个彩灯的状态。

讲道理,这个想法应该更自然,而且更容易想到。

不过思考无非就是平时的积累(装逼了哈哈哈哈,其实就是碰巧玩过一个类似的游戏,点亮所有的灯)加上关键时刻的灵感,

看到这个题目的时候,我的灵感就是数端点数目,

仔细一想才有了这种把操作分解的想法。

这个题目的操作是无序而且互相独立的,所以只需要统计每个彩灯的左边一共出现过多少端点就可以了。

所以这个题目有2种方案,都AC了。

第一种:树状数组。

代码:

#include<iostream>
using namespace std;


int list__[100001];
int main()
{
	int n,t, a;
	while (cin >> n >> t)
	{
		TreeArray opt(n);
		for (int i = 1; i <= n; i++)
		{
			cin >> list__[i];
		}
		while (t--)
		{
			cin >> a;
			opt.add(a, 1);
			cin >> a;
			opt.add(a, 1);
		}
		for (int i = 1; i <= n; i++)
		{
			cout << (list__[i] + opt.getSum(i)) % 2;
			if (i < n)cout << " ";
		}
		cout << endl;
	}
	return 0;
}

我把关闭同步的语句注释掉了,否则直接runtime error。。。。。。

然而,这个题目有一个更简单的方法,不需要任何数据结构,而且还略高效一点点。

因为这个题目就是恰好n次查询,所以用树状数组不如直接用最普通的数组了。

代码:

#include<iostream>
using namespace std;
 
int n;
int list[100001];	
int change[100002];
 
int main()
{
	int t, a;
	while (cin >> n >> t)
	{
		for (int i = 1; i <= n; i++)
		{
			cin >> list[i];
			change[i] = 0;
		}
		while (t--)
		{
			cin >> a;
			change[a]++;
			cin >> a;
			change[a + 1]++;
		}
		change[0] = 0;
		for (int i = 1; i <= n; i++)
		{
			change[i] += change[i - 1];
			cout << (list[i] + change[i]) % 2;
			if (i < n)cout << " ";
		}
		cout << endl;
	}
	return 0;
}

HDU 1166 敌兵布阵

题目:

Description

C国的死对头A国这段时间正在进行军事演习,所以C国间谍头子Derek和他手下Tidy又开始忙乎了。A国在海岸线沿直线布置了N个工兵营地,Derek和Tidy的任务就是要监视这些工兵营地的活动情况。由于采取了某种先进的监测手段,所以每个工兵营地的人数C国都掌握的一清二楚,每个工兵营地的人数都有可能发生变动,可能增加或减少若干人手,但这些都逃不过C国的监视。
中央情报局要研究敌人究竟演习什么战术,所以Tidy要随时向Derek汇报某一段连续的工兵营地一共有多少人,例如Derek问:“Tidy,马上汇报第3个营地到第10个营地共有多少人!”Tidy就要马上开始计算这一段的总人数并汇报。但敌兵营地的人数经常变动,而Derek每次询问的段都不一样,所以Tidy不得不每次都一个一个营地的去数,很快就精疲力尽了,Derek对Tidy的计算速度越来越不满:"你个死肥仔,算得这么慢,我炒你鱿鱼!”Tidy想:“你自己来算算看,这可真是一项累人的工作!我恨不得你炒我鱿鱼呢!”无奈之下,Tidy只好打电话向计算机专家Windbreaker求救,Windbreaker说:“死肥仔,叫你平时做多点acm题和看多点算法书,现在尝到苦果了吧!”Tidy说:"我知错了。。。"但Windbreaker已经挂掉电话了。Tidy很苦恼,这么算他真的会崩溃的,聪明的读者,你能写个程序帮他完成这项工作吗?不过如果你的程序效率不够高的话,Tidy还是会受到Derek的责骂的. 
Input

第一行一个整数T,表示有T组数据。 
每组数据第一行一个正整数N(N<=50000),表示敌人有N个工兵营地,接下来有N个正整数,第i个正整数ai代表第i个工兵营地里开始时有ai个人(1<=ai<=50)。 
接下来每行有一条命令,命令有4种形式: 
(1) Add i j,i和j为正整数,表示第i个营地增加j个人(j不超过30) 
(2)Sub i j ,i和j为正整数,表示第i个营地减少j个人(j不超过30); 
(3)Query i j ,i和j为正整数,i<=j,表示询问第i到第j个营地的总人数; 
(4)End 表示结束,这条命令在每组数据最后出现; 
每组数据最多有40000条命令 
Output

对第i组数据,首先输出“Case i:”和回车, 
对于每个Query询问,输出一个整数并回车,表示询问的段中的总人数,这个数保持在int以内。 
Sample Input

1
10
1 2 3 4 5 6 7 8 9 10
Query 1 3
Add 3 6
Query 2 7
Sub 10 2
Add 6 3
Query 3 10
End 
Sample Output

Case 1:
6
33
59

这个题目用树状数组或者线段树来做都可以,效率差不多。

树状数组代码:
 

#include<iostream>
#include<string.h>
using namespace std;


int main()
{
	int n,t, a, x, y;
	cin >> t;
	char ch[6];
	for (int cas = 1; cas <= t; cas++)
	{
		cin >> n;
		TreeArray<50000>opt(n);
		for (int i = 1; i <= n; i++)
		{
			scanf("%d", &a);
			opt.add(i, a);
		}
		printf("Case %d:\n", cas);
		while (scanf("%s", ch))
		{
			if (ch[0] == 'E')break;
			scanf("%d%d", &x, &y);
			if (ch[0] == 'A')opt.add(x, y);
			else if (ch[0] == 'S')opt.add(x, -y);
			else printf("%d\n", opt.getSum(y) - opt.getSum(x - 1));
		}
	}
	return 0;
}

POJ 2309 BST

题目:

Description

Consider an infinite full binary search tree (see the figure below), the numbers in the nodes are 1, 2, 3, .... In a subtree whose root node is X, we can get the minimum number in this subtree by repeating going down the left node until the last level, and we can also find the maximum number by going down the right node. Now you are given some queries as "What are the minimum and maximum numbers in the subtree whose root node is X?" Please try to find answers for there queries. 

Input

In the input, the first line contains an integer N, which represents the number of queries. In the next N lines, each contains a number representing a subtree with root number X (1 <= X <= 2  31 - 1).
Output

There are N lines in total, the i-th of which contains the answer for the i-th query.
Sample Input

2
8
10
Sample Output

1 15
9 11

代码:

#include<iostream>
using namespace std;
 
int main()
{	
	ios_base::sync_with_stdio(false);
	int t;
	cin >> t;
	long long k;
	for (int i = 1; i <= t; i++)
	{
		cin >> k;
		cout << k - (k&(-k)) + 1 << " " << k + (k&(-k)) - 1 << endl;
	}
	return 0;
}

代码实在是简单,不过这个图倒是很有意思。

首先,这个图和树状数组的图是很像的。

其次,第一行都是奇数,第二行都是2的倍数,第三行都是4的倍数。。。

所以,这个图和汉诺塔问题也有着紧密的联系。

POJ 2352 HDU 1541 Stars

题目:

Description

Astronomers often examine star maps where stars are represented by points on a plane and each star has Cartesian coordinates. Let the level of a star be an amount of the stars that are not higher and not to the right of the given star. Astronomers want to know the distribution of the levels of the stars. 
 


For example, look at the map shown on the figure above. Level of the star number 5 is equal to 3 (it's formed by three stars with a numbers 1, 2 and 4). And the levels of the stars numbered by 2 and 4 are 1. At this map there are only one star of the level 0, two stars of the level 1, one star of the level 2, and one star of the level 3. 

You are to write a program that will count the amounts of the stars of each level on a given map.
Input

The first line of the input file contains a number of stars N (1<=N<=15000). The following N lines describe coordinates of stars (two integers X and Y per line separated by a space, 0<=X,Y<=32000). There can be only one star at one point of the plane. Stars are listed in ascending order of Y coordinate. Stars with equal Y coordinates are listed in ascending order of X coordinate. 
Output

The output should contain N lines, one number per line. The first line contains amount of stars of the level 0, the second does amount of stars of the level 1 and so on, the last line contains amount of stars of the level N-1.
Sample Input

5
1 1
5 1
7 1
3 3
5 5

Sample Output

1
2
1
1
0

因为这个题目所给的输入很特殊,所以导致题目做起来很简单。

就是把一维的c数组不停的刷,相当于一行星星对应于c从左往右刷一遍。

这个和0-1背包问题的空间优化非常像

代码:

#include<iostream>
#include<string.h>
using namespace std;


int level[15001];

int main()
{
	int nn, s = 0, x, y;
	while (scanf("%d", &nn) != EOF) {
		memset(level, 0, sizeof(int)*(nn + 1));
		TreeArray<32000>opt(32001);
		for (int i = 0; i < nn; i++)
		{
			scanf("%d%d", &x, &y);
			opt.add(x + 1, 1);
			level[opt.getSum(x + 1) - 1]++;
		}
		for (int i = 0; i < nn; i++)printf("%d\n", level[i]);
	}
	return 0;
}

很明显可以看到,y在输入之后就没了,不做任何处理,也不调用y的值,很有意思吧

我还试过把n进行优化,然而这是不行的,n必须一开始就是最大值。

如果n从0开始,用x往上推的话,算出来的答案是错的。

而且,只要空间够大,本题log n的计算时间是很小的,只有输入输出是θ(n)的时间。

力扣 307. 区域和检索 - 数组可修改

给定一个整数数组  nums,求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和,包含 i,  j 两点。

update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。

示例:

Given nums = [1, 3, 5]

sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
说明:

数组仅可以在 update 函数下进行修改。
你可以假设 update 函数与 sumRange 函数的调用次数是均匀分布的。

暴力解法:

class NumArray {
public:
    vector<int>nums;
    NumArray(vector<int>& nums) {
        this->nums=nums;
    }
    
    void update(int i, int val) {
        nums[i]=val;
    }
    
    int sumRange(int i, int j) {
        int ans=0;
        for(int k=i;k<=j;k++)ans+=nums[k];
        return ans;
    }
};

树状数组:

class NumArray {
public:
	NumArray(vector<int>& nums) :opt(TreeArray{ int(nums.size()) })
	{
		for (int i = 0; i < nums.size(); i++)opt.add(i + 1, nums[i]);
		this->nums = nums;
	}

	void update(int i, int val) {
		opt.add(i + 1, val - nums[i]);
		nums[i] = val;
	}

	int sumRange(int i, int j) {
		return opt.getSum(j + 1) - opt.getSum(i + 1) + nums[i];
	}
	TreeArray<100000> opt;
	vector<int> nums;
};

力扣 2250. 统计包含每个点的矩形数目(离散化)

给你一个二维整数数组 rectangles ,其中 rectangles[i] = [li, hi] 表示第 i 个矩形长为 li 高为 hi 。给你一个二维整数数组 points ,其中 points[j] = [xj, yj] 是坐标为 (xj, yj) 的一个点。

第 i 个矩形的 左下角 在 (0, 0) 处,右上角 在 (li, hi) 。

请你返回一个整数数组 count ,长度为 points.length,其中 count[j]是 包含 第 j 个点的矩形数目。

如果 0 <= xj <= li 且 0 <= yj <= hi ,那么我们说第 i 个矩形包含第 j 个点。如果一个点刚好在矩形的 边上 ,这个点也被视为被矩形包含。

示例 1:

输入:rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]
输出:[2,1]
解释:
第一个矩形不包含任何点。
第二个矩形只包含一个点 (2, 1) 。
第三个矩形包含点 (2, 1) 和 (1, 4) 。
包含点 (2, 1) 的矩形数目为 2 。
包含点 (1, 4) 的矩形数目为 1 。
所以,我们返回 [2, 1] 。
示例 2:

输入:rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]
输出:[1,3]
解释:
第一个矩形只包含点 (1, 1) 。
第二个矩形只包含点 (1, 1) 。
第三个矩形包含点 (1, 3) 和 (1, 1) 。
包含点 (1, 3) 的矩形数目为 1 。
包含点 (1, 1) 的矩形数目为 3 。
所以,我们返回 [1, 3] 。
 

提示:

1 <= rectangles.length, points.length <= 5 * 104
rectangles[i].length == points[j].length == 2
1 <= li, xj <= 109
1 <= hi, yj <= 100
所有 rectangles 互不相同 。
所有 points 互不相同 。

class Solution {
public:
	vector<int> countRectangles(vector<vector<int>>& rectangles, vector<vector<int>>& points) {
		vector<int>x, y;
		x.reserve(rectangles.size() + points.size());
		y.reserve(rectangles.size() + points.size());
		for (auto p : rectangles)x.push_back(-p[0]), y.push_back(-p[1]);
		for (auto p : points)x.push_back(-p[0]), y.push_back(-p[1]);
		vector<int> vx = SortId(x), vy = SortId2(y);
		vector<int>ans(points.size());
		TreeArray<100000> opt(x.size());
		for (int i = 0; i < vx.size(); i++)
		{
			if (vx[i] < rectangles.size())
				opt.add(vy[vx[i]]+1, 1);
			else 
				ans[vx[i]- rectangles.size()] = opt.getSum(vy[vx[i]]+1);
		}
		return ans;
	}
};

四,二维树状数组

1,模板代码

二维树状数组和一维的好像好像!除了空间变大了一些貌似没有区别。

只要真的理解了一维树状数组,我感觉二维的应该是无师自通的,直接上代码。

#include<iostream>
#include<string.h>
using namespace std;

template<int maxLen = 1000>
class TreeArray2D
{
public:
	TreeArray2D(int len)//len是元素实际数量,元素id范围是[1,n]*[1,n]
	{
		this->n = len;
		for (int i = 0; i <= n; i++)memset(c[i], 0, sizeof(int)*(n + 1));
	}
	void add(int x, int y, int a = 1)
	{
		for (int i = x; i <= n; i += (i&(-i)))
			for (int j = y; j <= n; j += (j&(-j)))c[i][j] += a;
	}
	int getSum(int x, int y)
	{
		int s = 0;
		for (int i = x; i > 0; i -= (i&(-i)))
			for (int j = y; j > 0; j -= (j&(-j)))
				s += c[i][j];
		return s;
	}
private:
	int n;
	int c[maxLen +5][maxLen +5];
};

2,OJ实战

POJ 1195 Mobile phones

题目:


Description

Suppose that the fourth generation mobile phone base stations in the Tampere area operate as follows. The area is divided into squares. The squares form an S * S matrix with the rows and columns numbered from 0 to S-1. Each square contains a base station. The number of active mobile phones inside a square can change because a phone is moved from a square to another or a phone is switched on or off. At times, each base station reports the change in the number of active phones to the main base station along with the row and the column of the matrix. 

Write a program, which receives these reports and answers queries about the current total number of active mobile phones in any rectangle-shaped area. 
Input

The input is read from standard input as integers and the answers to the queries are written to standard output as integers. The input is encoded as follows. Each input comes on a separate line, and consists of one instruction integer and a number of parameter integers according to the following table. 


The values will always be in range, so there is no need to check them. In particular, if A is negative, it can be assumed that it will not reduce the square value below zero. The indexing starts at 0, e.g. for a table of size 4 * 4, we have 0 <= X <= 3 and 0 <= Y <= 3. 

Table size: 1 * 1 <= S * S <= 1024 * 1024 
Cell value V at any time: 0 <= V <= 32767 
Update amount: -32768 <= A <= 32767 
No of instructions in input: 3 <= U <= 60002 
Maximum number of phones in the whole table: M= 2^30 
Output

Your program should not answer anything to lines with an instruction other than 2. If the instruction is 2, then your program is expected to answer the query by writing the answer as a single line containing a single integer to standard output.
Sample Input

0 4
1 1 2 3
2 0 0 2 2 
1 1 1 2
1 1 2 -1
2 1 1 2 3 
3
Sample Output

3
4

不知道为什么这个题目给的时间尤其多,5000ms,反正我只用了516ms

代码:

#include<iostream>
#include<string.h>
using namespace std;



int main()
{
	int n, order, x, y, a, le, b, r, t;
	scanf("%d%d", &order, &n);
	TreeArray2D<1025>opt(n);
	while (scanf("%d", &order))
	{
		if (order == 3)break;
		if (order == 1)
		{
			scanf("%d%d%d", &x, &y, &a);
			x++, y++;
			opt.add(x, y, a);
		}
		else
		{
			scanf("%d%d%d%d", &le, &b, &r, &t);
			le++, b++, r++, t++;
			printf("%d\n", opt.getSum(r, t) - opt.getSum(le - 1, t) - opt.getSum(r, b - 1) + opt.getSum(le - 1, b - 1));
		}
	}
	return 0;
}

POJ 2155 Matrix (区间更新单点查询)

题目:

Given an N*N matrix A, whose elements are either 0 or 1. A[i, j] means the number in the i-th row and j-th column. Initially we have A[i, j] = 0 (1 <= i, j <= N). 

We can change the matrix in the following way. Given a rectangle whose upper-left corner is (x1, y1) and lower-right corner is (x2, y2), we change all the elements in the rectangle by using "not" operation (if it is a '0' then change it into '1' otherwise change it into '0'). To maintain the information of the matrix, you are asked to write a program to receive and execute two kinds of instructions. 

1. C x1 y1 x2 y2 (1 <= x1 <= x2 <= n, 1 <= y1 <= y2 <= n) changes the matrix by using the rectangle whose upper-left corner is (x1, y1) and lower-right corner is (x2, y2). 
2. Q x y (1 <= x, y <= n) querys A[x, y]. 
Input
The first line of the input is an integer X (X <= 10) representing the number of test cases. The following X blocks each represents a test case. 

The first line of each block contains two numbers N and T (2 <= N <= 1000, 1 <= T <= 50000) representing the size of the matrix and the number of the instructions. The following T lines each represents an instruction having the format "Q x y" or "C x1 y1 x2 y2", which has been described above. 
Output
For each querying output one line, which has an integer representing A[x, y]. 

There is a blank line between every two continuous test cases. 
Sample Input
1
2 10
C 2 1 2 2
Q 2 2
C 2 1 2 1
Q 1 1
C 1 1 2 1
C 1 2 1 2
C 1 1 2 2
Q 1 1
C 1 1 2 1
Q 2 1
Sample Output
1
0
0
1


题意:

对一个二维数组,每次更新一个矩形内所有的数,然后查询1个数

思路:

通过差分,转化成单点更新,区间查询问题

代码:

#include<iostream>
#include<string.h>
using namespace std;


int main()
{
	int n,X, t;
	cin >> X;
	while (X--)
	{
		scanf("%d%d", &n, &t);
		TreeArray2D<1000> opt(n);
		char c;
		int x1, y1, x2, y2;
		while (t--)
		{
			scanf("%c", &c);
			scanf("%c", &c);
			if (c == 'C')
			{
				scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
				opt.add(x1, y1), opt.add(x1, y2 + 1);
				opt.add(x2 + 1, y1), opt.add(x2 + 1, y2 + 1);
			}
			else
			{
				scanf("%d%d", &x1, &y1);
				printf("%d\n", opt.getSum(x1, y1) % 2);
			}
		}
		if (X)printf("\n");
	}
	return 0;
}

力扣 2536. 子矩阵元素加 1(区间更新单点查询)

给你一个正整数 n ,表示最初有一个 n x n 、下标从 0 开始的整数矩阵 mat ,矩阵中填满了 0 。

另给你一个二维整数数组 query 。针对每个查询 query[i] = [row1i, col1i, row2i, col2i] ,请你执行下述操作:

找出 左上角 为 (row1i, col1i) 且 右下角 为 (row2i, col2i) 的子矩阵,将子矩阵中的 每个元素 加 1 。也就是给所有满足 row1i <= x <= row2i 和 col1i <= y <= col2i 的 mat[x][y] 加 1 。
返回执行完所有操作后得到的矩阵 mat 。

示例 1:

输入:n = 3, queries = [[1,1,2,2],[0,0,1,1]]
输出:[[1,1,0],[1,2,1],[0,1,1]]
解释:上图所展示的分别是:初始矩阵、执行完第一个操作后的矩阵、执行完第二个操作后的矩阵。
- 第一个操作:将左上角为 (1, 1) 且右下角为 (2, 2) 的子矩阵中的每个元素加 1 。 
- 第二个操作:将左上角为 (0, 0) 且右下角为 (1, 1) 的子矩阵中的每个元素加 1 。 
示例 2:

输入:n = 2, queries = [[0,0,1,1]]
输出:[[1,1],[1,1]]
解释:上图所展示的分别是:初始矩阵、执行完第一个操作后的矩阵。 
- 第一个操作:将矩阵中的每个元素加 1 。
 

提示:

1 <= n <= 500
1 <= queries.length <= 104
0 <= row1i <= row2i < n
0 <= col1i <= col2i < n

class Solution {
public:
	vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {
		TreeArray2D<500> opt(n);
		for (auto q : queries) {
			opt.add(q[2] + 2, q[3] + 2, 1);
			opt.add(q[0]+1, q[3] + 2, -1);
			opt.add(q[2] + 2, q[1]+1, -1);
			opt.add(q[0]+1, q[1]+1, 1);
		}
		vector<vector<int>>ans(n, vector<int>(n));
		for (int i = 0; i < n; i++)for (int j = 0; j < n; j++) {
			ans[i][j] = opt.getSum(i+1, j+1);
		}
		return ans;
	}
};

五,支持在动态增长的数组中查询前缀最大值的树状数组

template<int maxLen = 100000>
class MaxTreeArray
{
public:
	MaxTreeArray(int len)//len是元素实际数量,元素id范围是[1,n]
	{
		this->n = len;
		memset(num, 0, sizeof(int)*(len + 1));
		memset(c, 0, sizeof(int)*(len + 1));
	}
	void add(int i, int x)
	{
		num[i + 1] += x;
		while (i <= n)
		{
			c[i] = max(c[i], x);
			i += (i&(-i));
		}
	}
	int getMaxId(int i) // 返回[1,i]这前i个数据中最大值位置,范围是[1,i]
	{
		int id = 1;
		while (i)
		{
			if (num[id] < num[c[i]])id = c[i];
			i -= (i&(-i));
		}
		return id;
	}
private:
	int n;
	int num[maxLen + 5];
	int c[maxLen + 5];
};

还没有测试过,不确定这个代码对不对。

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值