给一个序列长度为n(<=100,000) ,q(<=100)个询问
定义一个串的常数L(h)
if n < 2,
L(h)=0
if n ≥ 2,
max⌈∣∣hj−hij−i∣∣⌉
over all 1 ≤ i < j ≤ n
对每个询问(l,r) 给出a[l..r]的所有子串的L(h) 的和
显然最后会用到的L(h)是相邻的2个数,依次考虑它们对答案的贡献
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<functional>
#include<iostream>
#include<cmath>
#include<cctype>
#include<set>
#include<ctime>
using namespace std;
#define For(i,n) for(int i=1;i<=n;i++)
#define Fork(i,k,n) for(int i=k;i<=n;i++)
#define Rep(i,n) for(int i=0;i<n;i++)
#define ForD(i,n) for(int i=n;i;i--)
#define RepD(i,n) for(int i=n;i>=0;i--)
#define Forp(x) for(int p=pre[x];p;p=next[p])
#define Forpiter(x) for(int &p=iter[x];p;p=next[p])
#define Lson (x<<1)
#define Rson ((x<<1)+1)
#define MEM(a) memset(a,0,sizeof(a));
#define MEMI(a) memset(a,127,sizeof(a));
#define MEMi(a) memset(a,128,sizeof(a));
#define INF (2139062143)
#define F (100000007)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
typedef long long ll;
ll mul(ll a,ll b){return (a*b)%F;}
ll add(ll a,ll b){return (a+b)%F;}
ll sub(ll a,ll b){return (a-b+llabs(a-b)/F*F+F)%F;}
void upd(ll &a,ll b){a=(a%F+b%F)%F;}
set<int> S;
set<int>::iterator it;
#define MAXN (100000+10)
int n,q,a[MAXN],b[MAXN];
int read()
{
int x=0,f=1; char ch=getchar();
while(!isdigit(ch)) {if (ch=='-') f=-1; ch=getchar();}
while(isdigit(ch)) { x=x*10+ch-'0'; ch=getchar();}
return x*f;
}
pair<int,int> t[MAXN],ask[MAXN];
ll ans[MAXN]={0};
int main()
{
// freopen("D.in","r",stdin);
// freopen(".out","w",stdout);
cin>>n>>q;
For(i,n) cin>>a[i];
For(i,n-1) t[i]=mp( b[i] = abs(a[i]-a[i+1]) ,i);
sort(t+1,t+n);
S.insert(0); S.insert(n);
For(i,q) cin>>ask[i].fi>>ask[i].se;
ForD(i,n-1) {
int p=t[i].fi,m=t[i].se;
it=S.upper_bound(m);
int r=(*it);
it--;
int l=1+(*it);
// cout<<l<<" "<<m<<" "<<r<<endl;
S.insert(m);
For(j,q) {
int l2=max(l,ask[j].fi),r2=min(r,ask[j].se);
if (l2<=m && m<r2) ans[j]+=(ll)(m-l2+1)*(r2-m)*p;
}
}
For(i,q) cout<<ans[i]<<endl;
return 0;
}