跳到正文

个人记录

7.18 树状数组 总结

whr_1230约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年7月19日
收录
2025年12月12日
更新
2026年11月19日
篇幅
约 2 分钟

版本

  1. v1当前

7.18 树状数组 总结

U438237 ١١(❛ᴗ❛)【树状数组+线段树】-模板(单点修改+区间查询)

树状数组是一种支持单点修改和区间查询的,代码量小的数据结构。

性质

  1. 点x的高度是lowbit(x),即x二进制最低位1的位数。
  2. 点x的长度是lowbit(x)。
  3. 点x存储的是以x为结尾的,长度为lowbit(x)的区间答案。

重点

  1. lowbit(获得x的二进制最低位1的位数)
C++
int lowbit(int x)
{
	return x&-x;
}
  1. 修改
C++
void update(int x,int k)
{
	while(x<=n)
	{
		tr[x]+=k;
		x+=lowbit(x);
	}
}
  1. 查询
C++
int query(int x)
{
	int sum=0;
	while(x)
	{
		sum+=tr[x];
		x-=lowbit(x);
	}
	return sum;
}

P5057 [CQOI2006] 简单题

用差分的思想维护区间修改,单点查询,在输出答案记得取模2。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=1e6+10;
int n,m;
int a[maxn];
int tr[maxn];
int lowbit(int x)
{
	return x&-x;
}
void update(int x,int k)
{
	while(x<=n)
	{
		tr[x]+=k;
		x+=lowbit(x);
	}
}
int query(int x)
{
	int sum=0;
	while(x)
	{
		sum+=tr[x];
		x-=lowbit(x);
	}
	return sum;
}
signed main()
{
	cin>>n>>m;
	while(m--)
	{
		int op,x,y;
		cin>>op;
		if(op==1)
		{
			cin>>x>>y;
			update(x,1);
			update(y+1,-1);
		}
		else 
		{
			cin>>x;
			int cnt=query(x);
			cout<<cnt%2<<"\n";
		}
	}
	return 0;
}
原文