二分答案,注意l是max(a[i]+a[i+1]),r是sum_a
判断的时候用dp,设f[i]为i与1最少的相同颜色数,g[i]为i与1最多的相同颜色数,转移是f[i]=max(a[i]-(w-a[i-1]-(a[1]-g[i-1])),0),g[i]=min(a[1]-f[i-1],a[i]);
#include<iostream>
#include<cstdio>
using namespace std;
const int N=20005;
int n,a[N],f[N],g[N];
int read()
{
int r=0,f=1;
char p=getchar();
while(p>'9'||p<'0')
{
if(p=='-')
f=-1;
p=getchar();
}
while(p>='0'&&p<='9')
{
r=r*10+p-48;
p=getchar();
}
return r*f;
}
bool ok(int w)
{
f[1]=a[1],g[1]=a[1];
for(int i=2;i<=n;i++)
f[i]=max(a[i]-(w-a[i-1]-(a[1]-g[i-1])),0),g[i]=min(a[1]-f[i-1],a[i]);
return f[n]==0;
}
int main()
{
n=read();
for(int i=1;i<=n;i++)
a[i]=read();
a[n+1]=a[1];
int l=0,r=0,ans=0;
for(int i=1;i<=n;i++)
l=max(l,a[i]+a[i+1]),r+=a[i];
while(l<=r)
{
int mid=(l+r)>>1;
if(ok(mid))
r=mid-1,ans=mid;
else
l=mid+1;
}
printf("%d
",ans);
return 0;
}