可以用单调栈或线段树建出树,然后dsu on tree就好了。
#include<bits/stdc++.h>
using namespace std;
inline char nc(){
static char buf[100000],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline void Read(int& x){
char c=nc();
for(;c<'0'||c>'9';c=nc());
for(x=0;c>='0'&&c<='9';x=(x<<3)+(x<<1)+c-48,c=nc());
}
typedef long long ll;
typedef pair<int,int> abcd;
char ss[30];
int Len;
inline void Print(ll x){
if(!x){
putchar(48);putchar('\n');
return;
}
for(Len=0;x;x/=10)ss[++Len]=x%10;
while(Len)putchar(ss[Len--]+48);
putchar('\n');
}
#define fi first
#define se second
#define It set<abcd>::iterator
const int N=550010;
const int Q=400010;
abcd c[Q],d[N];
int k,n,m,q,a[N],w[N],num;
int l[Q],r[Q];
bool b[Q];
int p[N<<2];
int h[Q],nx[Q],t[Q];
int top[Q],sz[Q],son[Q];
int v[N],tot;
ll Ans[Q],cnt[N],Res;
inline void Down(int x){
p[x<<1]=p[x<<1|1]=p[x];
p[x]=0;
}
void Update(int x,int l,int r,int L,int R,int y){
if(l>R||r<L)return;
if(l>=L&&r<=R){
p[x]=y;
return;
}
if(p[x])Down(x);
int Mid=l+r>>1;
Update(x<<1,l,Mid,L,R,y);Update(x<<1|1,Mid+1,r,L,R,y);
}
int Query(int x,int l,int r,int y){
if(l==r)return p[x];
if(p[x])Down(x);
int Mid=l+r>>1;
if(y<=Mid)return Query(x<<1,l,Mid,y);
return Query(x<<1|1,Mid+1,r,y);
}
inline bool Cmp(abcd a,abcd b){
if(a.fi!=b.fi)return a.fi<b.fi;
return l[a.se]>l[b.se];
}
inline bool Cmp2(int x,int y){
return l[x]>l[y];
}
void Dfs(int x){
sz[x]=1;
for(int i=h[x];i;i=nx[i]){
int v=t[i];
Dfs(v);
sz[x]+=sz[v];
if(sz[v]>sz[son[x]])son[x]=v;
}
}
inline void Update(int y,int x){
if(v[w[x]]!=tot)v[w[x]]=tot,cnt[w[x]]=a[x];else cnt[w[x]]+=a[x];
Ans[y]=max(Ans[y],cnt[w[x]]);
}
void Solve(int x){
for(int i=h[x];i;i=nx[i])
if(t[i]!=son[x])Solve(t[i]),tot++;
if(son[x])Solve(son[x]);
Ans[x]=Ans[son[x]];
if(son[x]){
for(int i=l[x];i<l[son[x]];i++)Update(x,i);
for(int i=r[son[x]]+1;i<=r[x];i++)Update(x,i);
}else for(int i=l[x];i<=r[x];i++)Update(x,i);
}
inline void Add(int x,int y){
t[++num]=y;nx[num]=h[x];h[x]=num;
}
int main(){
Read(n);Read(q);
for(int i=1;i<=n;i++)Read(a[i]),d[i].fi=a[i],d[i].se=i;
sort(d+1,d+n+1);
w[d[1].se]=num=1;
for(int i=2;i<=n;i++)
if(d[i].fi==d[i-1].fi)w[d[i].se]=num;else w[d[i].se]=++num;
for(int i=1;i<=q;i++)Read(l[i]),Read(r[i]),c[i].fi=r[i]-l[i]+1,c[i].se=i;
sort(c+1,c+q+1,Cmp);
num=0;
for(int i=q;i;i--){
int t=Query(1,1,n,l[c[i].se]);
if(!t)b[c[i].se]=1;else Add(t,c[i].se);
Update(1,1,n,l[c[i].se],r[c[i].se],c[i].se);
}
for(int i=1;i<=q;i++)
if(b[i]){
Dfs(i);
Solve(i);
}
for(int i=1;i<=q;i++)Print(Ans[i]);
return 0;
}