paap111222333
Giới thiệu
include <iostream>
include <stack>
include <vector>
pragma GCC optimize("O3,unroll-loops")
using namespace std;
int n, A[1000001], leftMin[1000001], rightMin[1000001], leftMax[1000001], rightMax[1000001];
stack<int> s[4];
int main() {
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
for(int i=0;i<n;i++){
cin>>A[i];
}
for (int i = 0; i < n; i++) {
while (!s[0].empty() && A[s[0].top()] >= A[i]) {
s[0].pop();
}
leftMin[i] = s[0].empty() ? i + 1 : i - s[0].top();
s[0].push(i);
}
for (int i = n - 1; i >= 0; i--) {
while (!s[1].empty() && A[s[1].top()] > A[i]) {
s[1].pop();
}
rightMin[i] = s[1].empty() ? n - i : s[1].top() - i;
s[1].push(i);
}
for (int i = 0; i < n; i++) {
while (!s[2].empty() && A[s[2].top()] <= A[i]) {
s[2].pop();
}
leftMax[i] = s[2].empty() ? i + 1 : i - s[2].top();
s[2].push(i);
}
for (int i = n - 1; i >= 0; i--) {
while (!s[3].empty() && A[s[3].top()] < A[i]) {
s[3].pop();
}
rightMax[i] = s[3].empty() ? n - i : s[3].top() - i;
s[3].push(i);
}
long long totalWeight = 0;
for (int i = 0; i < n; i++) {
totalWeight += (long long)A[i] * (leftMax[i] * rightMax[i] - leftMin[i] * rightMin[i]);
}
cout<<totalWeight;
return 0;
}