跳到正文

个人记录

树状数组进阶总结

xgc88888888约 6 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

1.U438285 ١١(❛ᴗ❛)【树状数组】-数星星 Stars

题意:给定 nn 个点,定义每个点的等级是在该点左下方(含正左、正下)的点的数目,试统计每个等级有多少个点,即:

  • x[i]≤x[j]x[i]≤x[j]
  • y[i]≤y[j]y[i]≤y[j]

因为数组动态添加,即保证 y[i]≤y[j]y[i]≤y[j] ,只需考虑 y[i]≤y[j]y[i]≤y[j]

先统计答案,再以 xx 坐标为下标插入即可

Ac Code

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+7;
int n,q;
int cnt[N],c[N];
int lowbit(int x){
	return x&(-x);
}
void modify(int x,int v){
	while(x<=40000){
		c[x]+=v;
		x+=lowbit(x);
	}
	return;
}
int query(int x){
	int sum=0;
	while(x>0){
		sum+=c[x];
		x-=lowbit(x);
	}
	return sum;
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n;
	for(int i=1;i<=n;i++){
		int x,y;
		cin>>x>>y;
		x++;//有x=0的情况,防止死循环
		cnt[query(x)]++;
		modify(x,1);
	}
	for(int i=0;i<n;i++){
		cout<<cnt[i]<<'\n';
	}
	return 0;
} 

2.U438255 ١١(❛ᴗ❛)【树状数组】-校门外的树

区间修改,但区间查询

示例

如图,用两个树状数组,一个记录种树起点,一个记录种树终点

[l,r][l,r] 代表查询的区间,答案即是 [1,r][1,r] 中起点的数量 −- 区间 [1,l−1][1,l-1] 中终点的数量

Ac Code

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+7;
int n,k;
int c[N][2];
int lowbit(int x){
	return x&(-x);
}
void modify(int x,int v,int cnt){
	while(x<=n){
		c[x][cnt]+=v;
		x+=lowbit(x);
	}
	return;
}
int query(int x,int cnt){
	int sum=0;
	while(x>0){
		sum+=c[x][cnt];
		x-=lowbit(x);
	}
	return sum;
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>k;
	while(k--){
		int op,x,y;
		cin>>op>>x>>y;
		if(op==1){
            //记录起止点
			modify(x,1,0);
			modify(y,1,1);	
		}
		else{
			cout<<query(y,0)-query(x-1,1)<<'\n';	
		}
	}
	return 0;
}

3.U523492 ١١(❛ᴗ❛)【离散化】-非并列排名

模版题

离散化即将散开的每个数,通过下标集中,得出大小关系

优点:通过下标得出大小关系,缩小数据范围 (1−n)(1-n)

Ac Code

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+7;
struct node{
	int v,id;
}a[N];
bool cmp(node x,node y){
    //特判
	if(x.v==y.v){
        return x.id<y.id;
    }
	return x.v>y.v;
}
int n,pos[N];
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n;
    //离散化模版
	for(int i=1;i<=n;i++){
		cin>>a[i].v;
		a[i].id=i;//记录下标
	}
	sort(a+1,a+n+1,cmp);//排序下标
	for(int i=1;i<=n;i++){
		pos[a[i].id]=i;//记录排名
	}
	for(int i=1;i<=n;i++){
		cout<<pos[i]<<' ';
	}
	return 0;
}

4.U523499 ١١(❛ᴗ❛)【离散化】-并列大小

在模版基础上改改即可

Ac Code

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+7;
struct node{
	int v,id;
}a[N];
bool cmp(node x,node y){
	return x.v<y.v;
}
int n,pos[N];
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n;
    //离散化模版
	for(int i=1;i<=n;i++){
		cin>>a[i].v;
		a[i].id=i;
	}
	sort(a+1,a+n+1,cmp);
	int cnt=0;
	for(int i=1;i<=n;i++){
        //若何上个数大小不相等才上升名次
		if(a[i].v!=a[i-1].v){
			cnt++;
		}
		pos[a[i].id]=cnt;	
	}
	for(int i=1;i<=n;i++){
		cout<<pos[i]<<' ';
	}
	return 0;
}
原文