A function is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≤ K·|x - y| holds for all
. We'll deal with a more... discrete version of this term.
For an array , we define it's Lipschitz constant
as follows:
- if n < 2,
- if n ≥ 2,
over all 1 ≤ i < j ≤ n
In other words, is the smallest non-negative integer such that |h[i] - h[j]| ≤ L·|i - j| holds for all 1 ≤ i, j ≤ n.
You are given an array of size n and q queries of the form [l, r]. For each query, consider the subarray
; determine the sum of Lipschitz constants of all subarrays of
.
The first line of the input contains two space-separated integers n and q (2 ≤ n ≤ 100 000 and 1 ≤ q ≤ 100) — the number of elements in array and the number of queries respectively.
The second line contains n space-separated integers (
).
The following q lines describe queries. The i-th of those lines contains two space-separated integers li and ri (1 ≤ li < ri ≤ n).
Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer — the sum of Lipschitz constants of all subarrays of .
10 4 1 5 2 9 1 3 4 2 1 7 2 4 3 8 7 10 1 9
17 82 23 210
7 6 5 7 7 4 6 6 2 1 2 2 3 2 6 1 7 4 7 3 5
2 0 22 59 16 8
In the first query of the first sample, the Lipschitz constants of subarrays of with length at least 2 are:
The answer to the query is their sum.
题目大意:
L(h)的值是区间【L,R】内,abs(h[i]-h[j])/(i-j)的最大值。
现在有q个询问,每个询问表示询问区间【L,R】内,所有连续的子序列的L(h)的值的和。
思路:
①观察到是斜率的最大值,所以能够很容易考虑到有决策单调性。(比如位子i所选择的最优的位子是j,那么对于位子i+1来讲,肯定选取的位子是大于等于j的);而又考虑是两个值的差除以距离差,那么我们很容易考虑到问题选择的单调性还是相邻的(位子i所选取的最优一定是i-1);
②那么我们维护一个单调栈,栈顶元素最小,那么过程中,弹出栈顶的元素能够作用到的最右边的位子就是i-1;新加入进去的元素能够作用到的最左边的位子就是栈顶元素所在原来数组的位子+1.
③那么对于每个位子所能够贡献的价值就是L【i】*R【i】*a【i】;
那么对于每个查询,我们O(nq)去统计即可。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stack>
using namespace std;
#define ll __int64
struct node
{
ll val,pos;
}now,nex;
ll a[150000];
ll R[150000];
ll L[150000];
int main()
{
ll n,m;
while(~scanf("%I64d%I64d",&n,&m))
{
stack<node>s;
for(ll i=1;i<=n;i++)scanf("%I64d",&a[i]);
for(ll i=n;i>=1;i--)a[i]=abs(a[i]-a[i-1]);
for(ll i=1;i<=n;i++)
{
while(!s.empty())
{
now=s.top();
if(a[i]>now.val)
{
R[now.pos]=i-1;
s.pop();
}
else break;
}
if(s.size()==0)L[i]=1;
else
{
now=s.top();
L[i]=now.pos+1;
}
now.val=a[i],now.pos=i;
s.push(now);
}
while(!s.empty())
{
now=s.top();
R[now.pos]=n;
s.pop();
}
while(m--)
{
ll x,y;scanf("%I64d%I64d",&x,&y);
ll output=0;
for(ll i=x+1;i<=y;i++)
{
ll LL=max(x+1,L[i]);
ll RR=min(y,R[i]);
output+=(i-LL+1)*(RR-i+1)*a[i];
}
printf("%I64d\n",output);
}
}
}