[Template] Tree array 1

Go to: My own blog

topic

Luogu P3374 tree array 1

answer

The value that can be maintained with a tree array must satisfy interval addition (combining two intervals) and interval subtraction (breaking an interval) (for example: interval sum can be added and subtracted, but the maximum value of the interval can only be added but not subtracted). The function of the tree array is to dynamically maintain interval data and dynamic query. The basic purpose is to maintain interval sum (the following explanations take interval sum as an example).

Lowbit operation: lowbit(n) is defined as a non-negative integer n in the binary representation of the "lowest bit of 1 and all subsequent 0". (Example: n=10=(1010), lowbit(n)=2=(10))

In C++, in the complement representation, ~n=-1-n, lowbit(n)=n&(~n+1)=n&(-n).

In addition, c[x] represents the sum of all the numbers in the interval [x-lowbit(x)+1,x] of the sequence, so the interval [1,x] can be divided into (log x) segments, which is equivalent to binary decomposition process. (Example: x=7=(111),[1,7] is divided into [1,4],[5,6],[7,7], the interval length is 4,2,1 respectively)

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=5e5+5;
int n,m;
int sum[maxn];
inline int lowbit(int x) {return x&(-x);}
inline void add(int x,int y) //给第x个位置加y
{
	for( ;x<=n;x+=lowbit(x)) sum[x]+=y;
}
inline int ask(int x) //查询区间[1,x]的和 
{
	int ans=0;
	for( ;x;x-=lowbit(x)) ans+=sum[x];
	return ans;
}

int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++) 
	{
		int x; scanf("%d",&x);
		add(i,x);
	}
	for(int i=1;i<=m;i++)
	{
		int t,x,y; scanf("%d%d%d",&t,&x,&y);
		if(t==1) add(x,y);
		else {int ans=ask(y)-ask(x-1); printf("%d\n",ans);}
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/zjgmartin/article/details/108390120
Recommended