[单调栈]Imbalanced Array

I m b a l a n c e d A r r a y Imbalanced Array ImbalancedArray


题目描述

You are given an array a a a consisting of n n n 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] [1,4,1] is 9 9 9 , because there are 6 6 6 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 .

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

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

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

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

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

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

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

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


输入

The first line contains one integer n n n ( 1<=n<=106 ) — size of the array a a a .

The second line contains n n n integers a1,a2… an ( 1<=ai<=106) — elements of the array.


输出

Print one integer — the imbalance value of a a a .


样例输入

3
1 4 1


样例输出

9


code

#include<cstdio>
#include<iostream>
using namespace std;
long long n,s,tail,a[1000005],f[1000005],minl[1000005],minr[1000005],maxl[1000005],maxr[1000005];
int main()
{
	scanf("%lld",&n);
	for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
	f[1]=0;
	tail=1;
	for(int i=1;i<=n;i++)
	 if(a[i]>a[f[tail]])
	 {
	 	minl[i]=i-1;
	 	f[++tail]=i;
	 }
	 else 
	 {
	 	while(a[i]<a[f[tail]]&&tail>=1)tail--;
		minl[i]=f[tail];
		f[++tail]=i;
	 }
	f[1]=n+1; 
	tail=1;
	for(int i=n;i>=1;i--)
	 if(a[i]>a[f[tail]])
	 {
		minr[i]=i+1;
		f[++tail]=i;
	 }
	 else 
	 {
		while(a[i]<=a[f[tail]]&&tail>=1)tail--;
		minr[i]=f[tail];
		f[++tail]=i;
	 }
	a[0]=a[n+1]=2147483647;
	f[1]=0;
	tail=1;
	for(int i=1;i<=n;i++)
	 if(a[i]<a[f[tail]])
	 {
	 	maxl[i]=i-1;
	 	f[++tail]=i;
	 }
	 else
	 {
	 	while(a[i]>a[f[tail]]&&tail>=1)tail--;
		maxl[i]=f[tail];
		f[++tail]=i;
	 }
	f[1]=n+1;
	tail=1;
	for(int i=n;i>=1;i--)
	 if(a[i]<a[f[tail]])
	 {
	 	maxr[i]=i+1;
		f[++tail]=i;
	 }
	 else 
	 {
	 	while(a[i]>=a[f[tail]]&&tail>=1)tail--;
		maxr[i]=f[tail];
		f[++tail]=i;
	 }
	for(int i=1;i<=n;i++)
	 s+=a[i]*1ll*(1ll*(i-maxl[i])*(maxr[i]-i)-1ll*(i-minl[i])*(minr[i]-i));
	printf("%lld",s); 
}


posted @ 2020-08-13 09:24  unknown_future  阅读(57)  评论(0编辑  收藏  举报