跳到正文

个人记录

7.15总结

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

文章信息

发布
2025年7月17日
收录
2025年12月12日
更新
2026年11月10日
篇幅
约 4 分钟

版本

  1. v1当前

倍增

用一些特殊方法将数组转化为树或者图来维护修改和查询,优点是省时间,而缺点也明显是耗空间

U519510

板子题,没啥好说的

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
int f(int a) {
	int len=1;
	while(len<=a/2) {
		len*=2;
	}
	return len;
}
signed main() {
	int k;
	cin>>k;
	if(k==0) {
		cout<<-1;
		return 0;
	}
	cout<<f(k);
	return 0;
}

P3865

在此之前我们先要介绍st表
我们可以将倍增的过程转化为一个二进制的倍增过程,然后用一个表格储存,这个表就被称为st表,优点是可以做到O(1)的查询,而具体步骤就是从下标i开始枚举到2^k的最大最小值,因为每个数都会被两个区间覆盖,所以我们要取最大最小值

代码
return max(st[l][len],st[r-(1<<len)+1][len]);
C++
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+7;
int st[maxn][30];
int lg[maxn];
int n,m;
void st_init() {
	lg[0]=-1;
	for(int i=1;i<=n;i++) {
		lg[i]=lg[i/2]+1;
	}
	for(int len=1;(1<<len)<=n;len++) {
		for(int i=1;i+(1<<len)-1<=n;i++) {
			st[i][len]=max(st[i][len-1],st[i+(1<<(len-1))][len-1]);
		}
	}
	return;
}
int query(int l,int r) {
	int len=lg[r-l+1];
	return max(st[l][len],st[r-(1<<len)+1][len]);
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++) {
		cin>>st[i][0];
	}
	st_init();
	while(m--) {
		int l,r;
		cin>>l>>r;
		cout<<query(l,r)<<'\n';
	}
	return 0;
}

P1890

将max转为gcd就行,顺便补充一下gcd通过使用辗转相除法可以将时间复杂度降到接近O(1)

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+7;
int st[maxn][30];
int lg[maxn];
int n,m;
int gcd(int a,int b) {
	return b?gcd(b,a%b):a;
}
void st_init() {
	lg[0]=-1;
	for(int i=1;i<=n;i++) {
		lg[i]=lg[i/2]+1;
	}
	for(int len=1;(1<<len)<=n;len++) {
		for(int i=1;i+(1<<len)-1<=n;i++) {
			st[i][len]=gcd(st[i][len-1],st[i+(1<<(len-1))][len-1]);
		}
	}
	return;
}
int query(int l,int r) {
	int len=lg[r-l+1];
	return gcd(st[l][len],st[r-(1<<len)+1][len]);
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++) {
		cin>>st[i][0];
	}
	st_init();
	while(m--) {
		int l,r;
		cin>>l>>r;
		cout<<query(l,r)<<'\n';
	}
	return 0;
}
原文