Topic Address: Http://codeforces.com/contest/602/problem/D
Given N,q. N stands for n points, and the horizontal axis is 1 to N. The ordinate is given by the input, and the Q (q<100) problem is followed by the given interval [c,d]. Find the sum of the maximum slope absolute value of all substrings (two points in the substring).
The main point: it is easy to find that the maximum slope absolute value must be provided by two adjacent points, each adjacent point slope must have its jurisdiction (less it itself). The precedence queue is used to find the left jurisdiction and the right jurisdiction of the slope of the adjacent two points. The value provided by this slope is the ABS (slope) * (range to the left) * (range to the right). See code for details.
#include <cstdio> #include <algorithm> #include <cstring> #define N 100005 #define INF 1e9 typedef LONG
Long ll;
using namespace Std;
int a[n],b[n];
pair<int,int>q[n],tmp;
int vl[n],vr[n];
int n,m,startn,endn;
int main () {int i;
Freopen ("In.txt", "R", stdin);
scanf ("%d%d", &n,&m);
for (i=1;i<=n;i++) scanf ("%d", &a[i]);
for (i=1;i<n;i++)//maximum ABS (slope) must appear in the adjacent two dots//B[i]=abs (A[i+1]-a[i]);
B[0]=b[n]=inf;
startn=endn=0;
Tmp.first=b[0];tmp.second=0;
q[endn++]=tmp;
for (i=1;i<n;i++) {while (startn<endn&&q[endn-1].first<=b[i]) endn--;
Vl[i]=q[endn-1].second;
Tmp.first=b[i];tmp.second=i;
q[endn++]=tmp;
} startn=endn=0;
Tmp.first=b[n];tmp.second=n;
q[endn++]=tmp; for (i=n-1;i>=1;i--) {while (startn<endn&&q[endn-1].first<b[i]) endn--;//note here is less than or less than equal to prevent and after the Repeat calculation//Vr[i]=q[endn-1].seconD
Tmp.first=b[i];tmp.second=i;
q[endn++]=tmp;
int c,d;
while (m--) {scanf ("%d%d", &c,&d);
ll Ans=0;
for (i=c;i<d;i++) {ans+= (LL) (I-max (vl[i],c-1)) * (min (vr[i],d+1)-i-1) *b[i]);
printf ("%i64d\n", ans); //View the scope of this slope.
To the left can govern how far, right can govern how far//return 0;
}