石子合并终极通用版
#include<bits/stdc++.h> using namespace std ; int stone[50010]; int n,t,ans; void combine(int k) { int tem=stone[k]+stone[k-1];//合并k和k-1堆 ans+=tem; for(int i=k; i<t-1; i++) stone[i]=stone[i+1]; //k以后的往前移位 t--; int j; for(j=k-1; j>0&&stone[j-1]<tem; j--) stone[j]=stone[j-1]; //k-1以后的往后移位,找大于tem的位置 stone[j]=tem;//在j处插入tem while(j>=2&&stone[j-2]<=stone[j]) { //在新得到的序列里递归处理 int d=t-j;//为了回溯。。。 combine(j-1); j=t-d;//回溯 } } int main() { while(~scanf("%d",&n)) { if(n==0) break; for(int i=0; i<n; i++) scanf("%d",&stone[i]); t=1; ans=0; for(int i=1; i<n; i++) { stone[t++]=stone[i]; while(t>=3&&stone[t-3]<=stone[t-1]) combine(t-2);//从1开始遍历到结尾 } while(t>1) combine(t-1);//合并完后如果不为一堆再合并一次 printf("%d ",ans); } return 0; }