标签:ati std its efi nts for ace rom color
描述
Given a sequence, we define the seqence‘s value equals the difference between the largest element and the smallest element in the sequence. As an example, the value of sequence (3, 1, 7, 2) = 7-1 = 6.
Now, given a sequence S, output the sum of all value of consecutive subsequences.
输入
The first line has an integer N (2 ≤ N ≤ 300000) indicating the number of elements of the sequence. Then follows N lines, each line has a positive integer no larger than 108 indicating an element of the sequence.
输出
Output the requested sum.
样例输入
4
3
1
7
2
样例输出
31
解题思路: 化简公式可得求的是所有区间最大值的和-所有区间最小值的和 。维护单调找,计算每个元素的贡献。
#include <bits/stdc++.h> #define LL long long using namespace std; const int N=3e5+5; LL a[N],st[N]; int main() { int n,m,k; cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; LL ans=0,sum=0,top=0; for(int i=1;i<=n;i++){ while(top>0&&a[i]>a[st[top]]){ LL num=a[st[top]]; sum-=num*(st[top]-st[top-1]); top--; } st[++top]=i; sum+=a[i]*(st[top]-st[top-1]); ans+=sum; }//区间最大值和 sum=0,top=0; for(int i=1;i<=n;i++){ while(top>0&&a[i]<a[st[top]]){ LL num=a[st[top]]; sum-=num*(st[top]-st[top-1]); top--; } st[++top]=i; sum+=a[i]*(st[top]-st[top-1]); ans-=sum; }//区间最小值和 cout<<ans<<endl; }
标签:ati std its efi nts for ace rom color
原文地址:https://www.cnblogs.com/ww123/p/11634856.html