description
Given a sequence, we define the seqence's value equals the difference between the largest element and the smallest element in the sequence. As an example, the value of sequence (3, 1, 7, 2) = 7-1 = 6.
Now, given a sequence S, output the sum of all value of consecutive subsequences.
Entry
The first line has an integer N (2 ≤ N ≤ 300000) indicating the number of elements of the sequence. Then follows N lines, each line has a positive integer no larger than 108 indicating an element of the sequence.
Export
Output the requested sum.
Sample input
4
3
1
7
2
Sample Output
31
Problem-solving ideas: seeking simplification formula available to all sections and maximum - minimum and all sections. Maintenance monotonous look, calculate the contribution of each element.
#include <bits/stdc++.h> #define LL long long using namespace std; const int N=3e5+5; LL a[N],st[N]; int main() { int n,m,k; cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; LL ans=0,sum=0,top=0; for(int i=1;i<=n;i++){ while(top>0&&a[i]>a[st[top]]){ LL num=a[st[top]]; sum-=num*(st[top]-st[top-1]); top--; } st[++top]=i; sum+=a[i]*(st[top]-st[top-1]); ans+=sum; }//区间最大值和 sum=0,top=0; for(int i=1;i<=n;i++){ while(top>0&&a[i]<a[st[top]]){ NUM LL=A [ST [Top]]; SUM - NUM = * (ST [Top] -st [TOP- . 1 ]); Top - ; } ST [ ++ Top] = I; SUM + A = [I] * ( ST [Top] -st [TOP- . 1 ]); ANS - = SUM; } // interval and a minimum value COUT ANS << << endl; }