倍增基础-st总结
xgc88888888 · · 个人记录
1.U519510 ١١(❛ᴗ❛)【倍增】-最小线段合并
思想跟下一题表很像,每次减去
Ac Code
#include<bits/stdc++.h>
using namespace std;
int n;
int ans=0;
int get_max(int x){
int cnt=1;
if(x==1)return 1;
//x>=cnt*2变式,防止爆int
while(cnt<=x/2){
cnt*=2;
}
return cnt;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
//特判
if(n==0){
cout<<-1;
return 0;
}
//n一定会减到0
while(n){
n-=get_max(n);
ans++;//线段数增加
}
cout<<ans;
return 0;
}
本题运用了倍增的思想,把线段分为多个二次幂的子线段,我们也能将大问题分解为小问题,得出问题的答案
2.P3865 【模板】ST 表 && RMQ 问题
Ac Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+7;
int n,m,d;
int t=0;
int st[N][65];
int lg[N];
void st_init(){
lg[0]=-1;
//初始化时范围到N
for(int i=1;i<=N;i++){
lg[i]=lg[i/2]+1;
}
return ;
}
void st_insert(){
for(int i=1;i<=20;i++){
if(n-(1<<i)>=0){
int len=n-(1<<i)+1;
st[len][i]=max(st[len][i-1],st[len+(1<<(i-1))][i-1]);
}
else{
break;
}
}
return ;
}
int qiery(int l,int r){
int len=lg[r-l+1];
return max(st[l][len],st[r-(1<<len)+1][len]);
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>m>>d;
st_init();//初始化
while(m--){
char s;
int x;
cin>>s>>x;
if(s=='A'){
x+=t;
x%=d;
st[++n][0]=x;
st_insert();//插入
}
else{
t=qiery(n-x+1,n);//存上次查询的答案
cout<<t<<'\n';//查询
}
}
return 0;
}