《TZOJ4244:Sum》

主要在于对每个点贡献的思考。

单独看所有的方案数:每个点的贡献就是他是最大值的方案数*他的值 - 他是最小值的方案数*他的值。

对于最大值的方案数:我们找到他的左边第一个比他大的点L,右边第一个比他大的点r。

然后这个值可以分为两部分。两边分开独立的。i-L  + r-i。

和两边组合形成的方案数(i-L) * (r-i)。具体的边界是否要减1,按记得位置修改下就行。

那么求最小值也是一样的。

这里的话显然就是一个单调递增栈和单调递减栈来找左右的位置。

然后为了不特殊处理最后还在栈中的元素,我们在n+1位置都赋上一个特殊值即可

// Author: levil
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
const int N = 3e5+5;
const int M = 12005;
const LL Mod = 2008;
#define rg register
#define pi acos(-1)
#define INF 1e9
#define CT0 cin.tie(0),cout.tie(0)
#define IO ios::sync_with_stdio(false)
#define dbg(ax) cout << "now this num is " << ax << endl;
namespace FASTIO{
    inline LL read(){
        LL x = 0,f = 1;char c = getchar();
        while(c < '0' || c > '9'){if(c == '-') f = -1;c = getchar();}
        while(c >= '0' && c <= '9'){x = (x<<1)+(x<<3)+(c^48);c = getchar();}
        return x*f;
    }
    void print(int x){
        if(x < 0){x = -x;putchar('-');}
        if(x > 9) print(x/10);
        putchar(x%10+'0');
    }
}
using namespace FASTIO;
void FRE(){
/*freopen("data1.in","r",stdin);
freopen("data1.out","w",stdout);*/}

int a[N],S[N];
int Mx[N][2],Mi[N][2];//左-右
int main()
{
    int n;n = read();
    for(rg int i = 1;i <= n;++i) a[i] = read();
    int top = 0;
    a[n+1] = INF;
    for(rg int i = 1;i <= n+1;++i)//比它大
    {
        while(top != 0 && a[i] > a[S[top]])
        {
            if(top != 0) Mx[S[top]][0] = S[top-1];
            Mx[S[top]][1] = i;
            --top;
        }
        S[++top] = i;
    }
    LL sum1 = 0,sum2 = 0;
    for(rg int i = 1;i <= n;++i)
    {
        LL ma = (i-Mx[i][0]-1)+(Mx[i][1]-i-1);//左,右的单独方案数
        ma += 1LL*(i-Mx[i][0]-1)*(Mx[i][1]-i-1);
        sum1 += ma*a[i];
    }
    top = 0,a[n+1] = -1;
    for(rg int i = 1;i <= n+1;++i)
    {
        while(top != 0 && a[i] < a[S[top]])
        {
            if(top != 0) Mi[S[top]][0] = S[top-1];
            Mi[S[top]][1] = i;
            --top;
        }
        S[++top] = i;
    }
    for(rg int i = 1;i <= n;++i)
    {
        LL ma = (i-Mi[i][0]-1)+(Mi[i][1]-i-1);
        ma += 1LL*(i-Mi[i][0]-1)*(Mi[i][1]-i-1);
        sum2 += ma*a[i];
    }
    LL ans = sum1-sum2;
    printf("%lld
",ans);
    system("pause");
}
View Code
原文地址:https://www.cnblogs.com/zwjzwj/p/13577091.html