莫队。。处理 l[i] 左边第一个小于它的位置 然后处理一个链上前缀和的东西 就ok了
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define LL long long
using namespace std;
const int N=100010;
int n,Q,a[N],l[N],r[N],belong[N],top,
mn[N][18],st[N];
LL res,sum[N],sum2[N];
struct node{
int x,y,id;
LL ans;
}q[N];
bool cmp1(node a,node b){
return belong[a.x]<belong[b.x]||(belong[a.x]==belong[b.x]&&a.y<b.y);
}
bool cmp2(node a,node b){
return a.id<b.id;
}
int RMQ(int l,int r){
int k=0;
while((1<<(k+1))<=r-l+1) k++;
// cout<<l<<" "<<r<<" "<<k<<" "<<mn[l][k]<<" "<<mn[r-(1<<k)+1][k]<<endl;
return a[mn[l][k]]<a[mn[r-(1<<k)+1][k]]?mn[l][k]:mn[r-(1<<k)+1][k];
}
void init(){
scanf("%d%d",&n,&Q);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
mn[i][0]=i;
}
for(int i=1;i<=n;i++){
while(top&&a[st[top]]>a[i]) r[st[top--]]=i;
l[i]=a[st[top]]==a[i]?l[st[top]]:st[top];
st[++top]=i;
}
while(top) r[st[top--]]=n+1;
int size=(int)sqrt(n);
// cout<<endl;
for(int i=1;i<=n;i++){
sum[i]=sum[l[i]]+(LL)(i-l[i])*a[i];
}
for(int i=n;i>=1;i--){
sum2[i]=sum2[r[i]]+(LL)(r[i]-i)*a[i];
}
// for(int i=1;i<=n;i++) cout<<l[i]<<" "<<r[i]<<endl;
for(int i=1;i<=n;i++) belong[i]=(i-1)/size+1;
for(int j=1;j<=17;j++){
for(int i=1;i<=n;i++)
{
if(i+(1<<j)-1<=n){
if(a[mn[i][j-1]]<a[mn[i+(1<<(j-1))][j-1]])
mn[i][j]=mn[i][j-1];
else mn[i][j]=mn[i+(1<<(j-1))][j-1];
}
}
}
}
void add1(int l,int r,LL o){
// cout<<"======"<<endl;
int tmp=RMQ(l,r);
res+=o*(tmp-l+1)*a[tmp];
res+=o*(sum[r]-sum[tmp]);
}
void add2(int l,int r,LL o){
// cout<<"!!!!!!"<<endl;
int tmp=RMQ(l,r);
res+=o*(r-tmp+1)*a[tmp];
res+=o*(sum2[l]-sum2[tmp]);
}
void solve(){
int cur1=q[1].x,cur2=q[1].x-1;
for(int i=1;i<=Q;i++){
while(cur2<q[i].y) cur2++,add1(cur1,cur2,1);
while(cur2>q[i].y) add1(cur1,cur2,-1),cur2--;
while(cur1<q[i].x) add2(cur1,cur2,-1),cur1++;
while(cur1>q[i].x) cur1--,add2(cur1,cur2,1);
q[i].ans=res;
}
sort(q+1,q+1+Q,cmp2);
for(int i=1;i<=Q;i++){
printf("%lld\n",q[i].ans);
}
}
int main(){
init();
for(int i=1,x,y;i<=Q;i++){
scanf("%d%d",&q[i].x,&q[i].y);
q[i].id=i;
}
sort(q+1,q+1+Q,cmp1);
solve();
return 0;
}