跳到正文

算法·理论

【模板】ST表

xxxasybt2023约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年10月8日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1
WARNING

代码未经充分测试,正确性未知。

C++
template<typename T>struct maximum{constexpr T operator()(const T&a,const T&b)const{return std::max(a,b);}};
template<typename T>struct minimum{constexpr T operator()(const T&a,const T&b)const{return std::min(a,b);}};
template <typename T,typename C>
struct ST
{
	static const int N = 1e5+5,M = 20;
	static inline const C comp;
	static inline int lg[N];
	T rmq[N][M];
	void init(int n,T *a)
	{
		static auto __init = [](){
			lg[0] = -1;
			for (int i = 1;i < N;i ++) lg[i] = lg[i/2]+1;
			return 0;
		}();
		for (int i = 1;i <= n;i ++) rmq[i][0] = a[i];
		for (int i = 1;i <= lg[n];i ++)
			for (int j = 1;j <= n-(1<<i)+1;j ++)
				rmq[j][i] = comp(rmq[j][i-1],rmq[j+(1<<i-1)][i-1]);
	}
	T query(int l,int r) {return comp(rmq[l][lg[r-l+1]],rmq[r-(1<<lg[r-l+1])+1][lg[r-l+1]]);}
};
弃用
C++
template <typename T>
struct RMQ
{
	static const int N = 1e6+5,M = 21;
	T rmq[N][M]; int lg[N];
	inline T cmp(const T&a,const T&b) {return max(a,b);}
	void init(int n,T *a)
	{
		lg[0] = -1;
		for (int i = 1;i <= n;i ++) lg[i] = lg[i/2]+1,rmq[i][0] = a[i];
		for (int j = 1;j <= lg[n];j ++)
			for (int i = 1;i+(1<<j)-1 <= n;i ++)
				rmq[i][j] = cmp(rmq[i][j-1],rmq[i+(1<<j-1)][j-1]);
	}
	inline T query(int l,int r) {return cmp(rmq[l][lg[r-l+1]],rmq[r-(1<<lg[r-l+1])+1][lg[r-l+1]]);}
};
原文