• TOJ4244: Sum


    描述

    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;
    } 
  • 相关阅读:
    生成新的密钥
    django 静态文件
    django 外键操作
    (fields.E130) DecimalFields must define a 'decimal_places' attribute.
    Django模型的Field Types总结
    Django 数据模型的字段列表整理
    需要学习的东西
    最全面的 MySQL 索引详解
    mysql 递归查询
    项目里面常用方法
  • 原文地址:https://www.cnblogs.com/ww123/p/11634856.html
Copyright © 2020-2023  润新知