码迷,mamicode.com
首页 > 其他好文 > 详细

TOJ4244: Sum

时间:2019-10-08 14:34:06      阅读:73      评论:0      收藏:0      [点我收藏+]

标签: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 10indicating 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;
} 

 

TOJ4244: Sum

标签:ati   std   its   efi   nts   for   ace   rom   color   

原文地址:https://www.cnblogs.com/ww123/p/11634856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!