Description
defines an L (h) value of a sequence h of length n according to the Lipschitz condition:
n<2,l (h) = 0;
n>=2, (1<=i< j<=n)
now gives a sequence a with a length of N, gives a Q-query, and each query gives the sum of all the subsequence L values of a range [l,r], a sequence s={a[l],..., a[r]},
Input
First behavior two integers n and q denote sequence length and number of queries, the second row n integers ai represents this sequence, and then Q rows two integers per line L and r represent the query interval (2<=n<=1e6,1<=q<=100,0<=ai<= 1e8
Output
For each query, the value of the output L (s)
Sample Input
4
1 5 2 9 1 3 4 2 1 7
2 4
3 8
7 ten
1 9
Sample Output
"
"
210
Solution
Set x1< x2< x3,y1< y2< Y3, the following proof
may be set, then we have
so
so a sequence of L (h) =max (|h[i+ 1]-h[i]| (1<=i< N), then if the sum of all the subsequence L values of a sequence is required, only the range of |h[i+1]-h[i]| can be [l,r] (that is, the largest |h[i+1]-h[i]| in this interval), then the monotone stack can be used to solve such problems
Code
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> using namespace
Std
#define MAXN 111111 typedef long LL;
int N,q,a[maxn],b[maxn],s[maxn],top,l[maxn],r[maxn],l,r,len;
int main () {while (~scanf ("%d%d", &n,&q)) {for (int i=1;i<=n;i++) scanf ("%d", &a[i]);
while (q--) {scanf ("%d%d", &l,&r);
Len=r-l;
for (int i=l;i<r;i++) b[i-l+1]=abs (a[i]-a[i+1]);
Top=0;
for (int i=1;i<=len;i++) {while (Top&&b[i]>=b[s[top]]) top--;
L[i]=top==0?0:s[top];
S[++top]=i;
} top=0;
for (int i=len;i>=1;i--) {while (Top&&b[i]>b[s[top]]) top--;
R[i]=top==0?len+1:s[top];
S[++top]=i;
ll Ans=0;
for (int i=1;i<=len;i++) ans+=1ll* (I-l[i]) * (r[i]-i) *b[i];
printf ("%i64d\n", ans);
} return 0; }