思路:和普通石子合并不同的是可以首位合并那么我们吧数组开2倍后面n+1到2n存储1到n相同的东西,dp[l][r]表示从L-R区间的最大值,每次石子都是有之前的2堆合并的,所以枚举中间点即可,dp[l][r]=max(dp[l][r],dp[l][k]+dp[k+1][r]+val[l][r]),其中val是合并L-R区间所需的代价我们用前缀和即可算出。
#pragma GCC optimize(2)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<iomanip>
#include<cstring>
#include<time.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e6+10;
const int M=1e3+10;
const int inf=0x3f3f3f3f;
const int maxx=2e5+7;
const double eps=1e-6;
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return a*(b/gcd(a,b));
}
template <class T>
void read(T &x)
{
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-')
op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op)
x = -x;
}
template <class T>
void write(T x)
{
if(x < 0)
x = -x, putchar('-');
if(x >= 10)
write(x / 10);
putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
ll res=1%p;
while(b)
{
if(b&1)
res=res*a%p;
a=1ll*a*a%p;
b>>=1;
}
return res;
}
int f1[405][405];
int f2[405][405];
int w[405];
int s[405];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>w[i];
w[i+n]=w[i];
}
memset(f1,-inf,sizeof f1);
memset(f2,inf,sizeof f2);
for(int i=1;i<=2*n;i++) s[i]=s[i-1]+w[i];
for(int len=1;len<=n;len++)
{
for(int j=1;j+len-1<=n*2;j++)
{
int l=j,r=j+len-1;
if(len==1) f1[l][r]=f2[l][r]=0;
else{
for(int k=l;k<r;k++)
{
f1[l][r]=max(f1[l][r],f1[l][k]+f1[k+1][r]+s[r]-s[l-1]);
f2[l][r]=min(f2[l][r],f2[l][k]+f2[k+1][r]+s[r]-s[l-1]);
}
}
}
}
int res1=0,res2=inf;
for(int i=1;i<=n;i++){
res1=max(res1,f1[i][i+n-1]);
res2=min(res2,f2[i][i+n-1]);
}
cout<<res2<<endl;
cout<<res1<<endl;
return 0;
}