Imbalanced Array
题目描述
You are given an array a a consisting of 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] is 9 9 , because there are 6 6 different subsegments of this array:
[1] [1] (from index 1 1 to index 1 1 ), imbalance value is 0 0 ;
[1,4] [1,4] (from index 1 1 to index 2 2 ), imbalance value is 3 3 ;
[1,4,1] [1,4,1] (from index 1 1 to index 3 3 ), imbalance value is 3 3 ;
[4] [4] (from index 2 2 to index 2 2 ), imbalance value is 0 0 ;
[4,1] [4,1] (from index 2 2 to index 3 3 ), imbalance value is 3 3 ;
[1] [1] (from index 3 3 to index 3 3 ), imbalance value is 0 0 ;
You have to determine the imbalance value of the array a a .
输入格式
手动马赛克…这玩意儿是在是太难搞了,复制过来就双写,恕我不搞了…
输出格式
Print one integer — the imbalance value of a a .
题意翻译
对于给定由 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
解题思路
来左边跟我一起统计i在多少个子序列中最大,又在多少个集合里面最小,减一减就好了
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
long long n,a[1000010],ans;
long long top,t[1000010];
long long maxl[1000010],maxr[1000010],minl[1000010],minr[1000010];
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
a[0]=0x3f3f3f3f;
top=1;
for(int i=1;i<=n;i++)
{
while(a[t[top]]<=a[i]) top--;
maxl[i]=t[top];
t[++top]=i;
}
a[n+1]=0x3f3f3f3f;
top=1;
t[1]=n+1;
for(int i=n;i>0;i--)
{
while(a[i]>a[t[top]]) top--;
maxr[i]=t[top];
t[++top]=i;
}
for(int i=1;i<=n;i++)
ans+=a[i]*(i-maxl[i])*(maxr[i]-i);
a[0]=-0x3f3f3f3f;
top=1;
t[1]=0;
for(int i=1;i<=n;i++)
{
while(a[i]<=a[t[top]]) top--;
minl[i]=t[top];
t[++top]=i;
}
a[n+1]=-0x3f3f3f3f;
top=1;
t[1]=n+1;
for(int i=n;i>0;i--)
{
while(a[i]<a[t[top]]) top--;
minr[i]=t[top];
t[++top]=i;
}
for(int i=1;i<=n;i++)
ans-=a[i]*(i-minl[i])*(minr[i]-i);
cout<<ans<<endl;
return 0;
}
该博客介绍了洛谷CF817D问题,即计算数组的不平衡值,该值是数组所有子序列的最大值与最小值之差的总和。博主分享了解题思路,通过统计每个元素在子序列中作为最大值和最小值的次数,进行相应的计算来得出答案。
484

被折叠的 条评论
为什么被折叠?



