【洛谷 CF817D】Imbalanced Array【单调栈优化】

题目描述

原题

You are given an array aa consisting of nn elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.

For example, the imbalance value of array [1,4,1][1,4,1] is 99 , because there are 66 different subsegments of this array:

[1](from index 1 to index 1 ), imbalance value is 0;
[1,4] (from index 1 to index 2 ), imbalance value is 3 ;
[1,4,1](from index 1 to index 3 ), imbalance value is 3 ;
[4](from index 2 to index 2 ), imbalance value is 0 ;
[4,1] (from index 2 to index 3 ), imbalance value is 3 ;
[1] (from index 3 to index 3 ), imbalance value is 0 ;
You have to determine the imbalance value of the array a .

输入格式

The first line contains one integer nn ( 1<=n<=10^6) — size of the array a .

The second line contains nn integers a 1,a 2 … a n ( 1<=ai<=10^6) — elements of the array.

输出格式

Print one integer — the imbalance value of a .

题意翻译

对于给定由 n 个元素构成的数组。一个子数组的不平衡值是这个区间的最大值与最小值的差值。数组的不平衡值是它所有子数组的不平衡值的总和。

以下是数组[1,4,1]不平衡值为9的例子,共有6个子序列:

[1] (从第一号到第一号)不平衡值为 0;

[1, 4] (从第一号到第二号), 不平衡值为 3;

[1, 4, 1] (从第一号到第三号),不平衡值为 3;

[4] (从第二号到第二号),不平衡值为 0;

[4, 1] (从第二号到第三号),不平衡值为 3;

[1] (从第三号到第三号)不平衡值为 0;

输入输出样例

输入 #1

3
1 4 1

输出 #1

9

分析:

答案为max - min
我们要考虑如何计算这两个值
对于a[i] 设L[i]为a[i] 左边可延伸到的位置
R[i] 为a[i]右边可延伸到的位置
那么 max = (i - L[i] - 1)*(R[i] - i -1)
min则相反 以及O(n)维护单调栈 不必担心TLE

CODE:

#include<iostream>
#include<cstdio>
#include<algorithm>
#define inf 0x7f7f7f7f 
using namespace std;
struct FFF{
	long long v;
	int id;
}st[1000100];
struct node{
	int l,r;
}maxx[1000100],minn[1000100];
long long n,top,ans_,_ans,l,a[1000100];
int main(){
	scanf("%lld",&n);
	for(int i=1;i<=n;i++)
	    scanf("%lld",&a[i]);
	top=1,a[n+1]=-inf;  //建立边界
	for(int i=1;i<=n+1;i++){
		l=i;
		while(top&&st[top-1].v>=a[i]){  //递增找最小值
			top--;
			minn[st[top].id].r=i-1;  //被pop时记录右端点
		    l=minn[st[top].id].l;  //左端点尽量左
	    }
	    if(i<=n)
		   st[top].v=a[i],st[top].id=i,minn[st[top].id].l=l,top++;  //记录左端点 入栈
	}
	top=1,a[n+1]=inf,st[0].v=inf;
	for(int i=1;i<=n+1;i++){
		l=i;
		while(top&&st[top-1].v<=a[i]){  //递减找最大值
			top--;
			maxx[st[top].id].r=i-1;
		    l=maxx[st[top].id].l;
	    }
	    if(i<=n)
	       st[top].v=a[i],st[top].id=i,maxx[st[top].id].l=l,top++;  //与上面一致
	}
	for(int i=1;i<=n;i++)
	    ans_+=a[i]*(i-maxx[i].l+1)*(maxx[i].r-i+1);  //计算max
	for(int i=1;i<=n;i++)
	    _ans+=a[i]*(i-minn[i].l+1)*(minn[i].r-i+1);  //计算min
	printf("%lld",ans_-_ans);  //答案为两者之差
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值