zoukankan      html  css  js  c++  java
  • Minimum Sum

    题目描述

    One day, Snuke was given a permutation of length N, a1,a2,…,aN, from his friend.

    Find the following:

    Constraints
    1≤N≤200,000
    (a1,a2,…,aN) is a permutation of (1,2,…,N).

    输入

    The input is given from Standard Input in the following format:
    N
    a1 a2 … aN

    输出

    Print the answer.
    Note that the answer may not fit into a 32-bit integer.

    样例输入

    3
    2 1 3
    

    样例输出

    9
    
    这是一道单调栈
    单调栈的总结:https://blog.csdn.net/wubaizhe/article/details/70136174
    #include <bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    const int maxn = 2e5+10;
    struct node
    {
        ll pre;
        ll net;
        ll num;
    };
    stack<node>sp;
    ll s[maxn];
    int main()
    {
        ios::sync_with_stdio(false);
        int n;
        cin>>n;
        for(int i=1;i<=n;i++) cin>>s[i];
        ll ans=0;
        node fr,to;
        fr.net=fr.pre=1;
        fr.num=s[1];
        sp.push(fr);
        for(int i=2;i<=n;i++){
            to.num=s[i];
            to.pre=to.net=1;
            while(!sp.empty()&&to.num<=sp.top().num){
                fr=sp.top();
                sp.pop();
                if(!sp.empty()) sp.top().net+=fr.net;
                to.pre+=fr.pre;
                ans+=fr.pre*fr.num*fr.net;
            }
            sp.push(to);
        }
        while(!sp.empty())
        {
            fr=sp.top();
                sp.pop();
                if(!sp.empty()) sp.top().net+=fr.net;
                ans+=fr.pre*fr.num*fr.net;
        }
        cout<<ans<<endl;
        return 0;
    }
    View Code

     单调栈对求前后的有多少比他大/小很高效

    1.首先这个运算要简化成:前面的大值*后面的大值(紧接的并且加上本身)

    2.然后就是栈,极其烧脑┭┮﹏┭┮

    不要忘记努力,不要辜负自己 欢迎指正 QQ:1468580561
  • 相关阅读:
    POJ 1981 Circle and Points (扫描线)
    UVA 1514 Piece it together (二分图匹配)
    CodeForces 140D New Year Contest
    HDU 4863 Centroid of a Tree
    HDU 4865 Peter's Hobby
    HDU 4870 Rating
    HDU 4864 Task
    CodeForces 766E Mahmoud and a xor trip
    CodeForces 766D Mahmoud and a Dictionary
    CodeForces 767D Cartons of milk
  • 原文地址:https://www.cnblogs.com/smallocean/p/8822685.html
Copyright © 2011-2022 走看看