zoukankan      html  css  js  c++  java
  • 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数据库查询优化-事务-图书管理系统的搭建
    模型层字段-多表查询-神奇的双下划线查询-F,Q查询
    Django的View(视图)-settings源码的解析-模板层-模板语法
    Django路由层与视图层
    Django框架的前奏(安装及介绍)
    面向对象的三大特性
    一,类的初识
    一,对象初识
    装饰器
    闭包
  • 原文地址:https://www.cnblogs.com/ww123/p/11634856.html
Copyright © 2011-2022 走看看