AT2060 [AGC005B] Minimum Sum
题面
给你一个长为 \(n\) 的数列 \(a\),求
\[\sum_{l=1}^{n}{\sum_{r=l}^{n}{min\{a_l \sim a_r\}}}
\]
思路
考试题改的。
可以用单调栈算出贡献区间,然后乘法原理计算出总贡献。
具体见代码:
代码
// O(n)
#include <bits/stdc++.h>
#define int long long
using namespace std;
int a[300005];
int l[300005], r[300005];
int ll[300005], rr[300005];
int n;
int top, top2;
int st[300005];
int st2[300005];
long long ans;
//int ans1,ans2;
signed main() {
//freopen("sequence.in", "r", stdin);
//freopen("sequence.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
r[i] = n + 1;
rr[i] = n + 1;
}
for (int i = 1; i <= n; ++i) {
while (top && a[st[top]] > a[i]) {
r[st[top--]] = i;
}
l[i] = st[top];
st[++top] = i;
}
for (int i = 1; i <= n; i++) {
ans += (r[i] - i) * (i - l[i]) * a[i];
//ans += (rr[i] - i) * (i - ll[i]) * a[i];
}
cout << ans << '\n';
return 0;
}