题意:就是求出所有区间最大值减去最小值的和。
解法:学了一波单调栈。
用单调栈正反跑一遍得到每个数字若是最小值的时候能在的区间的范围。
正反跑一遍得到每个数字若是最大值的时候能在区间的范围。
然后求一求每个数字在多少个区间里面,求出贡献度,然后即可得出答案。
代码如下:
#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<utility>
#include<stack>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
typedef pair<int, int> pii;
const int maxn = 1e6 + 5;
long long a[maxn];
int n;
stack <pii> sta;
struct node {
long long left, right;
}Min[maxn], Max[maxn];
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%I64d", &a[i]);
}
sta.push(pii(a[0], 0));//选取小的
Min[0].left = 0;
for(int i = 1; i < n; i++) {
int tmp = i;
while(!sta.empty() && sta.top().first >= a[i]) {
tmp = sta.top().second;
sta.pop();
}
if(tmp != i)
Min[i].left = Min[tmp].left;
else
Min[i].left = i;
sta.push(pii(a[i], i));
}
while(!sta.empty())
sta.pop();
sta.push(pii(a[n - 1], n - 1));
Min[n - 1].right = n - 1;
for(int i = n - 2; i >= 0; i--) {
int tmp = i;
while(!sta.empty() && sta.top().first > a[i]) {
tmp = sta.top().second;
sta.pop();
}
if(tmp != i)
Min[i].right = Min[tmp].right;
else
Min[i].right = i;
sta.push(pii(a[i], i));
}
while(!sta.empty())//选取大的
sta.pop();
sta.push(pii(a[0], 0));
Max[0].left = 0;
for(int i = 1; i < n; i++) {
int tmp = i;
while(!sta.empty() && sta.top().first <= a[i]) {
tmp = sta.top().second;
sta.pop();
}
if(tmp != i)
Max[i].left = Max[tmp].left;
else
Max[i].left = i;
sta.push(pii(a[i], i));
}
while(!sta.empty())
sta.pop();
sta.push(pii(a[n - 1], n - 1));
Max[n - 1].right = n - 1;
for(int i = n - 2; i >= 0; i--) {
int tmp = i;
while(!sta.empty() && sta.top().first < a[i]) {
tmp = sta.top().second;
sta.pop();
}
if(tmp != i)
Max[i].right = Max[tmp].right;
else
Max[i].right = i;
sta.push(pii(a[i], i));
}
long long sum1 = 0, sum2 = 0;//求出答案
for(int i = 0; i < n; i++) {
sum1 += ((Min[i].right - i) + (i - Min[i].left) + (Min[i].right - i) * (i - Min[i].left)) * a[i];
}
for(int i = 0; i < n; i++) {
sum2 += ((Max[i].right - i) + (i - Max[i].left) + (Max[i].right - i) * (i - Max[i].left)) * a[i];
}
printf("%I64d\n", sum2 - sum1);
return 0;
}