跳到正文

科技·工程

一些封装好的数据结构

chenzifan7497约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年2月13日
收录
2026年2月15日
更新
2026年11月3日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

树状数组(1-index)

C++
template<typename T>
class BIT{
private:std::vector<T> c;int n;T Ori;
public:
	BIT(int size,T *a,T x){n=size; Ori=x;
		std::vector<T> tmp(n+1,0); c.resize(n+1);
		for(int i=1;i<=n;i++)tmp[i]=tmp[i-1]+a[i];
		for(int i=1;i<=n;i++)c[i]=tmp[i]-tmp[i-(i&-i)];
	}
	void init(T x){for(int i=1;i<=n;i++)c[i]=Ori;}
	void add(int x,T y){for(;x<=n;x+=x&-x)c[x]=c[x]+y;}
	T ask(int x){T r=Ori;for(;x;x-=x&-x)r=r+c[x];return r;}
	T ask(int l,int r){return ask(r)-ask(l-1);}
};
//使用:BIT<变量类型> 名字(原数组,大小,该类型单位元)

线性ST表(0-index):

一发A掉由乃救爷爷

C++
template<typename T,typename Cmp=std::less<T>>
class rmq{
private:
	typedef long long ll; typedef unsigned long long ull;
	Cmp comp; int blg(const int x){return x>>6;}
	int log_2(const ull &x){return 63-__builtin_clzll(x);}
	T Max(const T &x,const T &y){return comp(x,y)? y:x;}
	std::vector<T> st[32],pre,suf,a;
	std::vector<ull> ins; int B,K,n;
public:
	rmq(int size,T *ar){
		n=size;	B=(n+63)/64; K=log_2((ull)B)+1;
		ins.resize(n+64); a.resize(n+64);
		pre.resize(n+64); suf.resize(n+64);
		for(int i=0;i<n;++i)a[i]=ar[i];
		for(int i=0;i<K;++i)st[i].resize(B-(1<<i)+1);
		for(int i=0;i<B;++i){
			int l=i<<6,r=std::min(n,(i+1)<<6);
			T tmp=ar[l];
			for(int j=l;j<r;++j)pre[j]=tmp=Max(tmp,ar[j]);
			tmp=ar[r-1];
			for(int j=r-1;j>=l;--j)suf[j]=tmp=Max(tmp,ar[j]);
			st[0][i]=tmp;
		}
		for(int k=1;k<K;++k)for(int i=0;i+(1<<k)-1<B;++i)
			st[k][i]=Max(st[k-1][i],st[k-1][i+(1<<(k-1))]);
		int stk[80],top=0; memset(stk,0,sizeof stk);
		for(int i=0;i<B;++i){
			int l=i<<6,r=std::min(n,(i+1)<<6);
			top=0; ull state=0;
			for(int j=l;j<r;++j){
				while(top&&comp(ar[stk[top]],ar[j]))
					state^=1ull<<(stk[top--]-l);
				state^=1ull<<(j-l); ins[j]=state; stk[++top]=j;
			}
		}
	}
	T ask(int l,int r){
		if(blg(l)==blg(r)){
			int bl=l&-64,br=bl+63;
			if(l==bl)return pre[r];
			if(r==br)return suf[l];
			ull x=ins[r]&(~((1ull<<(l-bl))-1));
			return a[bl+__builtin_ctzll(x)];
		}
		int L=blg(l),R=blg(r);
		T res=Max(pre[r],suf[l]);
		if(L+2<=R){
			int k=log_2((ull)(R-L-1));
			res=Max(res,Max(st[k][L+1],st[k][R-(1<<k)]));
		} return res;
	}
};
//使用:rmq<类型,比较器(默认为大的,可像stl一样传入比较器,如果是<即大的优先,反之小的)> 名字(大小(注意是0-index),原数组)
原文