Luo Gu [P4393] Sequence

Title effect: Given a sequence of length N, each two adjacent elements can be combined at the cost of larger of the two values, the value after integration of both is also a large value, combined request N- after the minimum cost is the number 1.

Solution:
In addition to the maximum, each value will only be consolidated once, the combined cost of this must be that a maximum value left and right maximum smaller. How to solve the problem translates into the left and right of each element is greater than the value of the first element, monotonous stack sweep it again.
Note: If the same elements, such as 4223, two intermediate 2 will generate an error in calculating the final answer is the way to avoid the calculated value is greater than the right of each element taken equal to, greater than left to take.

code show as below

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
const int inf=0x3f3f3f3f;
typedef long long LL;

int n,a[maxn],l[maxn],r[maxn],stk[maxn],top;
LL ans;

int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    
    a[0]=a[n+1]=inf;
    for(int i=1;i<=n+1;i++){
        while(top&&a[stk[top]]<=a[i])r[stk[top--]]=i;
        stk[++top]=i;
    }
    top=0;
    for(int i=n;~i;i--){
        while(top&&a[stk[top]]<a[i])l[stk[top--]]=i;
        stk[++top]=i;
    }
    for(int i=1;i<=n;i++){
        if(l[i]<1&&r[i]>n)continue;
        if(l[i]>=1&&r[i]<=n)ans+=min(a[l[i]],a[r[i]]);
        else if(r[i]>n)ans+=a[l[i]];
        else if(l[i]<1)ans+=a[r[i]];
    }
    printf("%lld\n",ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/wzj-xhjbk/p/10950324.html