【CodeForce】817D Imbalanced Array
time limit per test:2 seconds
memory limit per test:256 megabytes
inputstandard input
outputstandard output
Description
You are given an array a consisting of 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] is 9, because there are 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.
Input
The first line contains one integer n (1 ≤ n ≤ 106) — size of the array a.
The second line contains n integers a1, a2… an (1 ≤ ai ≤ 106) — elements of the array.
Output
Print one integer — the imbalance value of a.
Sample Input
3
1 4 1
Sample Output
9
翻译
对于给定由 n 个元素构成的数组。一个子数组的不平衡值是这个区间的最大值与最小值的差值。数组的不平衡值是它所有子数组的不平衡值的总和。
以下是数组[1,4,1]不平衡值为9的例子,共有6个子序列:
[1] (从第一号到第一号)不平衡值为 0;
[1, 4] (从第一号到第二号), 不平衡值为 3;
[1, 4, 1] (从第一号到第三号),不平衡值为 3;
[4] (从第二号到第二号),不平衡值为 0;
[4, 1] (从第二号到第三号),不平衡值为 3;
[1] (从第三号到第三号)不平衡值为 0;
输入输出样例
输入
3
1 4 1
输出
9
思路
我们考虑每一个数对答案的贡献, 在一段连续的区间中, 这个数要么作为最大值, 要么作为最小值, 这样我们就设L[i]是第 i 个数它往左最大可以到的位置, R[i]是 i 往右最大可以到的位置, 这样答案就加上
ans += a[i] ×(i - L[i])×(R[i] - i ). 同理一样找最小的位置, ans-= a[i] ×(i - L[i])×(R[i] - i ), 然后输出答案即可.
找位置可以用单调栈,保存之前的位置,删除不符合条件的位置,加入当前位置。
代码
#include<iostream>
#include<cstdio>
using namespace std;
long long a[1000010],b[1000010],mn[1000010],mx[1000010],mxl[1000010],mxr[1000010],mnl[1000010],mnr[1000010];
int main()
{
long long n,i,ans=0,mns,mxs;
scanf("%lld",&n);
for(i=1;i<=n;scanf("%lld",&a[i]),b[i]=a[i],i++);
a[0]=a[n+1]=-100000000000,b[0]=b[n+1]=100000000000;
for(mns=mxs=1,mn[1]=0,mx[1]=0,i=1;i<=n;i++)//往左找最大(小)到的位置.
{
for(;a[i]<=a[mn[mns]];mns--);
mnl[i]=mn[mns],mn[++mns]=i;
for(;b[i]>=b[mx[mxs]];mxs--);
mxl[i]=mx[mxs],mx[++mxs]=i;
}
for(mns=mxs=1,mn[1]=mx[1]=n+1,i=n;i>0;i--)//往右找最大(小)到的位置.
{
for(;a[i]<a[mn[mns]];mns--);//没有=
mnr[i]=mn[mns],mn[++mns]=i;
for(;b[i]>b[mx[mxs]];mxs--);
mxr[i]=mx[mxs],mx[++mxs]=i;
}
for(i=1;i<=n;i++)
ans+=a[i]*(i-mxl[i])*(mxr[i]-i)-a[i]*(i-mnl[i])*(mnr[i]-i);
printf("%lld",ans);
return 0;
}