题意
给出一个长为 的正整数序列 。接下来有两种操作共 次:
1 l r,表示将 开方并下取整,即令2 l r,表示将 平方,即令 。
没错,我是直接复制过来的,因为原题面已经够简洁了。
做法
看到区间修改,很难不让人想到线段树,这里介绍我的做法,这道题的线段树是只有懒标记的(至少我的做法只有懒标记)。
我们发现如果直接模拟, 做 次平方操作,算出来的数就是 ,直接大爆炸,写高精度都救不了你,但又不能直接模,因为考虑到操作一平方并向下取整,发现一个数模后再开方和开方再模的值不一样,例如: 但 , 不等于 。
那有什么办法处理呢? 我们发现 最后的值 可以表示成 先做了 (后面简写成 )次开方操作后再进行 次平方操作。
记 做了 次开方操作后为 ,则 。
举个例子: 假如 如果依次进行了一下操作( 为开方操作, 为平方操作): 这时 ,那么 等于 , 就等于 。 我们发现第二个操作和第三个操作的作用被抵消了,所以相对于这个数先做了 次开方操作后再进行 次平方操作。
易发现(计算 和 ): 假如此时 要处理开方操作:
- 如果此时的 那么之前的平方操作的作用就与这次的开方操作抵消, 的值就减一,即跟新 。
- 当 ,无法抵消, 就加一,即跟新 。
如果是平方操作就直接给 加一。
得到 和 后,计算 还有几个问题:
- 我们在开方时,发现开到 就要退出开方了,这样最多只会开个 次,能保证时间复杂度。
- 在平方时,要平方 次,直接算肯定超时,观察到 ,利用费马小定理 ,所以 ,用快速幂这样时间复杂度就变成 。
优化
直接暴力维护,可以做到 。
聪明的同学肯定能想到用线段树来维护。 怎么维护呢? 我们直接把 和 当作懒标记来维护,那原本的含义就变了,变成了一段区间的数在上一次下放(即 pushdown 操作)之后经过若干次操作后的值相当于先做了 次开方操作( 为线段树中的某个节点),在进行 次平方操作。
在 pushdown 操作中设 为当前节点, 分别为左儿子和右儿子。 易得:
void push(int v){
int L=v*2,R=v*2+1;
dn[L]+=max(0ll,dn[v]-up[L]);
up[L]=max(0ll,up[L]-dn[v]);
up[L]+=up[v];
dn[R]+=max(0ll,dn[v]-up[R]);
up[R]=max(0ll,up[R]-dn[v]);
up[R]+=up[v];
dn[v]=up[v]=0; //记得懒标记归零
}在做完后把懒标记下放即可得到每个数的 和 ,算 即可。
总时间复杂度
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=3e5+100,mod=998244353;
int id,t,n,m;
ll up[4*N],dn[4*N],a[N],mi[N];
ll qmi(ll x,ll y){
ll res=1;
while(y){
if(y&1) res=res*x%mod;
x=x*x%mod; y>>=1;
}
return res;
}
void debug(int v,int tl,int tr){
cout<<v<<"#"<<tl<<" "<<tr<<" "<<up[v]<<" "<<dn[v]<<endl;
}
void fact(){
mi[0]=1;
for(int i=1;i<=N-10;i++)
mi[i]=mi[i-1]*2%(mod-1);
}
void push(int v){
int L=v*2,R=v*2+1;
dn[L]+=max(0ll,dn[v]-up[L]);
up[L]=max(0ll,up[L]-dn[v]);
up[L]+=up[v];
dn[R]+=max(0ll,dn[v]-up[R]);
up[R]=max(0ll,up[R]-dn[v]);
up[R]+=up[v];
dn[v]=up[v]=0;
}
void update(int v,int tl,int tr,int l,int r,int s){
if(l>r) return ;
if(tl==l&&tr==r){
if(s==2) up[v]++;
else{
if(up[v]) up[v]--;
else dn[v]++;
}
}else{
push(v);
int tm=(tl+tr)>>1,L=v*2,R=v*2+1;
update(L,tl,tm,l,min(tm,r),s);
update(R,tm+1,tr,max(tm+1,l),r,s);
}
// debug(v,tl,tr);
}
void ask(int v,int tl,int tr){
// debug(v,tl,tr);
if(tl==tr){
while(a[tl]!=1&&dn[v]--) a[tl]=sqrt(a[tl]);
if(a[tl]!=1) a[tl]=qmi(a[tl],mi[up[v]]);
}else{
push(v);
int tm=(tl+tr)>>1,L=v*2,R=v*2+1;
ask(L,tl,tm); ask(R,tm+1,tr);
}
}
void build(int v,int tl,int tr){
if(tl==tr) dn[v]=up[v]=0;
else{
int tm=(tl+tr)>>1,L=v*2,R=v*2+1;
build(L,tl,tm); build(R,tm+1,tr);
dn[v]=up[v]=0;
}
}
int main(){
// freopen("sq.in","r",stdin);
// freopen("sq.out","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
fact();
// cin>>id>>t;
t=1;
while(t--){
cin>>n>>m;
build(1,1,n);
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=1;i<=m;i++){
int op,l,r; cin>>op>>l>>r;
update(1,1,n,l,r,op);
}
ask(1,1,n);
ll ans=0;
for(int i=1;i<=n;i++)
ans=(ans+a[i])%mod;
cout<<ans<<"\n";
}
return 0;
}