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.
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.
Print one integer — the imbalance value of a.
3
1 4 1
9
题意:给你n个数,一个区间的贡献是区间最大值-区间最小值,求所有区间贡献和。
思路:首先想到n*n的rmq,明显超时。
换个角度,枚举每个数作为最小值的区间个数,枚举每个数作为最大值的区间个数;
怎么算呢,例如求最小值的区间,找出左边有x个比其大的,右边x个比其大的,区间的个数为x*y;
这个用单调栈可以O(n)处理,注意需要半开半闭;
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<iostream> #include<cstdio> #include<cmath> #include<string> #include<queue> #include<algorithm> #include<stack> #include<cstring> #include<vector> #include<list> #include<set> #include<map> #include<bitset> #include<time.h> using namespace std; #define LL long long #define pi (4*atan(1.0)) #define eps 1e-4 #define bug(x) cout<<"bug"<<x<<endl; const int N=1e6+10,M=1e6+10,inf=2147483647,mod=1e9+7; const LL INF=1e18+10,MOD=1e9+7; int a[N],d[N]; int zn[N],yn[N]; int zx[N],yx[N]; int main() { int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); a[0]=0; int k=0;d[++k]=0; for(int i=1;i<=n;i++) { while(a[d[k]]>=a[i])k--; zn[i]=d[k]; d[++k]=i; } a[n+1]=0; k=0;d[++k]=n+1; for(int i=n;i>=1;i--) { while(a[d[k]]>a[i])k--; yn[i]=d[k]; d[++k]=i; } a[0]=1e6+10; k=0;d[++k]=0; for(int i=1;i<=n;i++) { while(a[d[k]]<=a[i])k--; zx[i]=d[k]; d[++k]=i; } a[n+1]=1e6+10; k=0;d[++k]=n+1; for(int i=n;i>=1;i--) { while(a[d[k]]<a[i])k--; yx[i]=d[k]; d[++k]=i; } LL ans=0; for(int i=1;i<=n;i++) { ans+=1LL*(yx[i]-i)*(i-zx[i])*a[i]; ans-=1LL*(yn[i]-i)*(i-zn[i])*a[i]; } cout<<ans<<endl; return 0; }