我发现没人用dfs,所以我写了个代码
不讲思路
include<iostream>
include<algorithm>
include<cstdio>
using namespace std; const int maxn=50005; const int inf=0x7fffffff;//2147483647 int n,m,t,ans,stone[maxn]; void dfs(int k){ int tmp=stone[k-1]+stone[k]; ans+=tmp;t--; for(int i=k;i<t;++i)stone[i]=stone[i+1];//元素左移,表示删掉了一个元素 int j=0;k--; for(j=k;stone[j-1]<tmp;--j)stone[j]=stone[j-1];//元素右移,找到第一个满足条件的j stone[j]=tmp;//将tmp插到j后面 while(j>=3&&stone[j-2]<=stone[j]){//继续向前查找是否还有满足条件的情况 int d=t-j;//保存当前t离操作点的距离d dfs(j-1);//合并第j-1堆和第j-2堆石子 j=t-d;//设置新的操作点j } } int main(){ while(~scanf("%d",&n)&&n){ for(int i=1;i<=n;++i)scanf("%d",&stone[i]); t=2,ans=0;stone[0]=stone[n+1]=inf; for(int i=2;i<=n;++i){ stone[t++]=stone[i]; while(t>3&&stone[t-3]<=stone[t-1])dfs(t-2);//表示当前至少有3堆石子,并且满足stone[k-1]<=stone[k+1],k=t-2,就合并第t-3和第t-2堆石子 } while(t>2)dfs(t-1);//如果剩下的堆数至少为3-1=2堆,则继续合并,直至剩下一堆石子 printf("%d\n",ans); } return 0; }