链接:https://ac.nowcoder.com/acm/contest/223/C
来源:牛客网
题目描述
给出长度为n的序列a,其中第i个元素为
,定义区间(l,r)的价值为
![](https://i-blog.csdnimg.cn/blog_migrate/7d08f81f155f092309998d19c6be9ffe.png)
![](https://i-blog.csdnimg.cn/blog_migrate/7eb43507a5c8e796a86d4f7839525a34.png)
请你计算出
![](https://i-blog.csdnimg.cn/blog_migrate/9024406342e1a1644ec9c006035943a1.png)
输入描述:
第一行输入数据组数T
对于每组数据,第一行为一个整数n,表示序列长度
接下来一行有n个数,表示序列内的元素
输出描述:
对于每组数据,输出一个整数表示答案
示例1
备注:
![](https://i-blog.csdnimg.cn/blog_migrate/8fc0dba106ee9ac8a4d47d98c32cdf68.png)
不保证数据随机生成!
题意 : 题目经过几步简单的化简便可以知道我们要求的是任意一个区间中的最大值与最小值的差去累加
思路分析:暴力的 n^2 做法比较好想到
将上面的式子再进行一步化简可以得到的任意一个区间的最大值总和 - 任意一个区间最小值的总和
对于上式的两部分我们可以分别去求,用单调栈即可
例如在求最大值的和累加时,去维护一个单调递减的栈,具体看代码就懂了
#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;
}