题目:
题解:
尽量多让小的数字被合并
维护一个单调递减的栈。如果新进来一个数字,大于栈顶元素的话就弹栈,注意这里加入合并值的时候,如果里面那个数字更小的话就先合并里面的,不然就先和新的合并(贪)
小于栈顶就入栈咯
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#define LL long long
#define N 1000005
using namespace std;
int stack[N];
int main()
{
LL ans=0;int n,i;
scanf("%d",&n);
int top=0;
for (i=1;i<=n;i++)
{
int x;scanf("%d",&x);
while (x>=stack[top] && top)
{
if (x>=stack[top-1] && top>1)//比再前一个数大的话就先把以前的合并完
ans+=stack[top-1];
else ans+=x;
top--;
}
stack[++top]=x;
}
while (top!=1){ans+=stack[top-1]; top--;}
printf("%lld",ans);
}