#436. 子串的最大差
http://oj.daimayuan.top/problem/436
使用两次单调栈
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6;
class Node {
public:
long long int val,num;
int lma,rma;
int lmi,rmi;
};
Node a[N];
long long subArrayRanges(int n) {
stack<Node>icrs,dcrs; //升降
icrs.push(a[1]);
dcrs.push(a[1]);
for(int i = 2 ; i <= n ; i++) {
while(icrs.size() && icrs.top().val <= a[i].val ) { //升
int j = icrs.top().num;
a[j].rma = i;
icrs.pop();
}
if(icrs.size())
a[i].lma = icrs.top().num;
else a[i].lma = 0;
icrs.push(a[i]);
while(dcrs.size() && dcrs.top().val >= a[i].val ) { //降
int j = dcrs.top().num;
a[j].rmi = i;
dcrs.pop();
}
if(dcrs.size())
a[i].lmi = dcrs.top().num;
else a[i].lmi = 0;
dcrs.push(a[i]);
}
while(icrs.size()) {
int j = icrs.top().num;
icrs.pop();
a[j].rma = n+1;
icrs.size();
}
while(dcrs.size()) {
int j = dcrs.top().num;
dcrs.pop();
a[j].rmi = n+1;
dcrs.size();
}
long long sum = 0;
for(int i = 1 ; i <= n ; i++) {
sum += a[i].val*(a[i].rma - i)*(i - a[i].lma);
sum -= a[i].val*(a[i].rmi - i)*(i - a[i].lmi);
}
return sum;
}
int main() {
int n;
cin >> n;
for(int i = 1 ; i <= n ; i++) {
cin >> a[i].val;
a[i].num = i;
}
cout << subArrayRanges(n);
}

浙公网安备 33010602011771号