跳到正文

个人记录

树状数组进阶总结

the133lvlone约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年7月20日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 5 分钟

版本

  1. v1当前

T1

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int p,n,a[15002],C[32002],Q;
void b(int x,int y)
{
	while(x<32002)
	{
		C[x]+=y;
		x+=(x&(-x));
	}
	return;
}
int c(int x)
{
	Q=0;
	while(x)
	{
		Q+=C[x];
		x-=(x&(-x));
	}
	return Q;
}
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>p;
		a[c(p+1)]++;
		b(p+1,1);
		cin>>p;
	}
	for(int i=0;i<n;i++)
	{
		cout<<a[i]<<endl;
	}
}
php
坐标记为点

T2

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int P,n,a[50002],C[50002],Q,q,r,m;
void p(int x,int y)
{
	while(x<=n)
	{
		a[x]+=y;
		x+=(x&(-x));
	}
	return;
}
void b(int x,int y)
{
	while(x<=n)
	{
		C[x]+=y;
		x+=(x&(-x));
	}
	return;
}
int d(int x) 
{
	Q=0;
	while(x)
	{
		Q+=a[x];
		x-=(x&(-x));
	}
	return Q;
}
int c(int x)
{
	Q=0;
	while(x)
	{
		Q+=C[x];
		x-=(x&(-x));
	}
	return Q;
}
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	while(m--)
	{
		cin>>P>>q>>r;
		if(P&1)
		{
			p(q,1);
			b(r,1);
		}
		else
		{
			cout<<d(r)-c(q-1)<<endl;
		}
	}
	return 0;
}
php
尾部的种树开头数-头部的种树结尾数(中间的结尾数不算)

T3

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int P,n,a[100002],Q,q,r,m;
struct P
{
	int a,b;
	bool operator<(const P &B)const
	{
		if(a==B.a)
		{
			return b<B.b;
		}
		return a>B.a;
	}
}C[100002];
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>C[i].a;
		C[i].b=i;
	}
	sort(C+1,C+n+1);
	for(int i=1;i<=n;i++)
	{
		a[C[i].b]=i;
	}
	for(int i=1;i<=n;i++)
	{
		cout<<a[i]<<' ';
	}
	return 0;
}
php
离散化模版,将一组离散的数映射进1-数字数的区间里

T4

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int P,n,a[100002],Q,q,r;
struct P
{
	int a,b;
	bool operator<(const P &B)const
	{
		if(a==B.a)
		{
			return b<B.b;
		}
		return a<B.a;
	}
}C[100002];
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>C[i].a;
		C[i].b=i;
	}
	sort(C+1,C+n+1);
	for(int i=1;i<=n;i++)
	{
		if(C[i-1].a==C[i].a)
		{
			a[C[i].b]=q;
		}
		else
		{
			q++;
			a[C[i].b]=q;
		}
	}
	for(int i=1;i<=n;i++)
	{
		cout<<a[i]<<' ';
	}
	return 0;
}
php
离散化变种
原文