可以分开计算,先计算所有区间内的最大值之和,再减去所有区间的最小值之和。
#include <iostream> #include <stdio.h> #include <string.h> #include <time.h> #include <string> #include <stack> #include <algorithm> using namespace std; #define gc p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin), p1 == p2) ? EOF : *p1++; inline int read(){ static char buf[1000000], *p1 = buf, *p2 = buf; register int x = false; register char ch = gc; register bool sgn = false; while (ch != '-' && (ch < '0' || ch > '9')) ch = gc; if (ch == '-') sgn = true, ch = gc; while (ch >= '0'&& ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = gc; return sgn ? -x : x; } #ifdef LOCAL #define TIME cout << "RuningTime: " << clock() << "ms\n", 0 #else #define TIME 0 #endif typedef long long ll; const int N = 3e6 + 10; const int mod = 998244353; int a[N]; ll f[N]; int stk[N]; int n; ll calc1(int flag) { for (int i = 1; i <= n; i++) f[i] = 0; int top = 0; ll ans = 0, sum = 0; for (int i = 1; i <= n; i++) { while (top && (flag == 0 ? a[stk[top]] > a[i] : a[stk[top]] < a[i])) //递增 or 递减 top--; f[i] += 1LL * (i - stk[top]) * a[i]; f[i] += f[stk[top]]; stk[++top] = i; ans += f[i]; } return ans; } int main() { #ifdef LOCAL freopen("E:/input.txt", "r", stdin); #endif while (cin >> n) { for (int i = 1; i <= n; i++) scanf("%d", &a[i]); cout << calc1(1) - calc1(0) << endl; } return TIME; }