P1090 [NOIP2004 提高组] 合并果子 / [USACO06NOV] Fence Repair G - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include <iostream>
using namespace std ;
const int N = 10010 ;
int n , st[N] ;
int main ()
{
scanf ("%d",&n) ;
for (int i = 1;i <= n;i++)
scanf ("%d",&st[i]) ;
int res = 0 ;
while (n > 1)
{
int l = 1 , r = 2 ;
if (st[l] > st[r]) swap (l,r) ;
for (int i = 3;i <= n;i++)
{
if (st[i] < st[l])
{
r = l ;
l = i ;
}
else if (st[i] < st[r])
r = i ;
}
int t = st[l] + st[r] ;
res += t ;
if (l == n) swap (l,r) ;
st[l] = t ;
st[r] = st[n] ;
n-- ;
}
cout << res << endl ;
return 0 ;
}