The clever thing is that when the number of people is an odd number, the solution is to select the first person from the left as far as possible. If the number is an even number, select the person from the left as far as possible. If the number is an odd number, select from the right as far as possible.
Then, list the possible number of gifts in two parts to see if the problem is met. The first person and the last person do not select a duplicate.
Conclusion: redefinition of global variables may lead to errors. Therefore, you should be cautious when you fail to check the global variables.
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn = 100010;int a[maxn],left[maxn],right[maxn];int n;bool test(int p){ int x=a[1],y=p-a[1]; left[1]=x;right[1]=0; for(int i=2;i<=n;i++) { if(i%2==1) { right[i]=min(y-right[i-1],a[i]); left[i]=a[i]-right[i]; } else { left[i]=min(x-left[i-1],a[i]); right[i]=a[i]-left[i]; } } return left[n]==0;}int main(){ while(scanf("%d",&n)!=EOF) { if(n==0) break; for(int i=1;i<=n;i++) scanf("%d",&a[i]); if(n==1) { printf("%d\n",a[1]); continue; } a[n+1]=a[1]; int ans1=0,ans2=0; for(int i=1;i<=n;i++) { ans1=max(ans1,a[i]+a[i+1]); } if(n%2==1) { for(int i=1;i<=n;i++) { ans2=max(ans2,a[i]*3); } while(ans1<ans2) { int m=ans1+(ans2-ans1)/2; if(test(m)) ans2=m; else ans1=m+1; } } printf("%d\n",ans1); } return 0;}