树状数组(二叉索引树)

2023-11-05

目录

一,树状数组

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个彩灯的状态。

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

不过思考无非就是平时的积累(装逼了哈哈哈哈,其实就是碰巧玩过一个类似的游戏,点亮所有的灯https://blog.csdn.net/nameofcsdn/article/details/52100217)加上关键时刻的灵感,

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

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

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

所以这个题目有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];
};

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

树状数组(二叉索引树) 的相关文章

随机推荐

  • Android Studio更新Gradle版本

    Android Studio更新Gradle版本 1 在File分栏下 点击Project Structure 2 按照图示步骤操作 选中Project 点击Android Gradle Plugin Version复选框下三角符号 选择需
  • 2022.0306避障小车学习1

    要求 使用stm32f103单片机 应用RTOS实时系统 使用超声波模块 oled屏 l298n直流步进电机 驱动模块和小车底盘 思路 在任务里用超声波实时测出距障碍物的距离 并将距离显示在oled屏上 再根据判断距离大小调用前进或者后退那
  • web应用开发实战 - node.js

    了解Node js Node js 是一个基于 Chrome JavaScript 运行时建立的一个平台 Node js 是一个基于 Chrome V8 引擎的 JavaScript 运行时 Node js是运行在服务端上的 JavaScr
  • 单页面引入vue和element

    引入vue 1 可以直接在页面中引入 2 https cdn jsdelivr net npm vue 2 dist vue js 打开该链接下载vue 存放在本地 引入element 方法同上
  • 交换机的简单描述

    工作原理 1 交换机有张表 MAC地址表 一开始未通讯之前 MAC地址表是空的 2 同一个局域网中主机A访问主机B 3 主机A会将自己的MAC地址和对面的MAC地址封装进数据帧 自己的是源MAC地址 对面是目 的MAC地址 4 交换机会收到
  • [极客大挑战 2019]HardSQL 1

    极客大挑战 2019 HardSQL 1 首先打开题目 明显的发现这是一个sql注入的题 我们先用 和 测试是否有注入报错 发现用 时报错 所以这题很明显是有sql注入的 于是我们就利用用语句 admin or 1 1 测试得到 发现这里是
  • c++ 笔记1

    c 笔记 1 inline内联函数 2 构造函数初始化 3 构造函数重载注意事项 4 常量成员函数 5 参数传递和返回值使用const引用 6 友元 7 运算符重载this指针 8 规范化代码一 complex h complex test
  • jdbc连接mysql的语法_JDBC 连接MySQL实例详解

    JDBC连接MySQL JDBC连接MySQL 加载及注册JDBC驱动程序 Class forName com mysql jdbc Driver Class forName com mysql jdbc Driver newInstanc
  • 2021年中职组“网络安全”赛项 杭州市竞赛任务书

    2021年中职组 网络安全 赛项 杭州市竞赛任务书 一 竞赛时间 总计 360分钟 二 竞赛阶段 三 竞赛任务书内容 拓扑图 一 A模块基础设施设置 安全加固 200分 一 项目和任务描述 假定你是某企业的网络安全工程师 对于企业的服务器系
  • HashSet添加元素的过程

    文章目录 HashSet添加元素的过程 HashSet添加元素的过程 底层结构 数组 链表
  • MySQL数据库是非关系_关系型数据库和非关系型数据库的理解

    综合百度百科和自己的理解整理以下内容 便于日常用到时进行查找 如下 一 关系型数据库 1 含义 关系型数据库 是指采用了关系模型来组织数据的数据库 其以行和列的形式存储数据 以便于用户理解 关系型数据库这一系列的行和列被称为表 一组表组成了
  • pcb上模拟地和数字地怎么隔离

    p 谢谢了 学习中 p oh mygod Post at 2006 2 20 10 45 00 p 注意把数字地隔离 p p 直接打到主地或者单点接地 p br
  • SSL/TLS一键配置工具-IISCrypto

    IIS Crypto 是一个免费工具 使管理员能够在 Windows Server 2008 2012 2016 2019 和 2022 上启用或禁用协议 密码 哈希和密钥交换算法 允许您重新排序 IIS 提供的 SSL TLS 密码套件
  • C++ 知识点/面试题目总结 (八股文)

    C 知识点 面试题目总结 八股文 1 C和C 的区别 2 构造函数后面的冒号有什么用 3 函数后面 default和 delete有什么用 4 类的大小和什么有关系 5 struct和typedef struct什么区别 6 函数后面加co
  • 【数据结构与算法学习】图的深度优先遍历(DFS算法)

    目录 一 什么是图的遍历 二 深度优先遍历 DFS 的基本思想 三 深度优先遍历 DFS 的步骤详解 四 深度优先遍历 DFS 的代码实现 一 什么是图的遍历 图的遍历 指的是从图中的任一顶点出发 对图中的所有顶点访问一次且只访问一次 图的
  • 洛谷P1088火星人(C++)

    导语 这篇题解 如果你是不知道什么是全排列 的童鞋 自己去小墙角面壁思过5秒钟 不是 是让你按照以下顺序食用题解 题目 gt 全排列函数 纯手码写法 gt 思路 gt 全排列函数 next permutation gt AC代码 gt 总结
  • FPGA-仿真读写bmp图片

    文章目录 位图说明 位图 Verilog代码实现 python处理代码 附 最近想完成FPGA图像处理 由于没有开发板 就像通过仿真完成 之前像的是通过python 将图像转化为txt文本 最后利用verilog 读取txt文件导入 对像素
  • 华为深信服信息安全从业者考试认证大全(cwasp/cisp/nisp sisp-pte......

    证书是IT从业者知识水平能力的一个体现 考证同时也是拓展自身知识的一个方法 近年来 安全行业风生水起 各种认证层出不穷 眼花缭乱 这里不对任何一个证书做评价 只是做出介绍 在国内 对任何事物的评价都会引起围攻 所以笔者不敢妄谈一个证书的含金
  • 库文件中找不到符号问题:CMAKE_CXX_FLAGS: -fvisibility=hidden

    问题描述 编译出来的预测库发现找不到符号 但是相关源文件的确编译到库里了 定位问题 cmake配置中打开了以下开关 set CMAKE CXX FLAGS CMAKE CXX FLAGS fvisibility hidden fvisibi
  • 树状数组(二叉索引树)

    目录 一 树状数组 1 树状数组 2 区间更新单点查询 3 离散化 二 模板代码 三 OJ实战 CodeForces 706B Interesting drink CSU 1770 按钮控制彩灯实验 HDU 1166 敌兵布阵 POJ 23