链接:https://ac.nowcoder.com/acm/contest/223/C
来源:牛客网
第一行输入数据组数T
对于每组数据,第一行为一个整数n,表示序列长度
接下来一行有n个数,表示序列内的元素
对于每组数据,输出一个整数表示答案
#define ll long long
const ll maxn = 1e5+5;
ll n;
ll a[maxn], sta[maxn];
void solve() {
ll top = 0;
ll sum = 0, ans = 0;
for(ll i = 1; i <= n; i++){ // 下降
while(top > 0 && a[sta[top]] < a[i]) {
ll num = a[sta[top]];
sum -= num*(sta[top]-sta[top-1]);
top--;
}
sta[++top] = i;
sum += a[i]*(sta[top]-sta[top-1]);
ans += sum;
}
top = 0, sum = 0;
for(ll i = 1; i <= n; i++){ // 上升
while(top > 0 && a[sta[top]] > a[i]){
ll num = a[sta[top]];
sum -= num*(sta[top]-sta[top-1]);
top--;
}
sta[++top] = i;
sum += a[i]*(sta[top]-sta[top-1]);
ans -= sum;
}
cout << ans << ‘\n‘;
}
int main() {
ll t;
cin >> t;
while(t--){
scanf("%lld", &n);
for(ll i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
solve();
}
return 0;
}
原文:https://www.cnblogs.com/ccut-ry/p/9895593.html