题目链接:https://cn.vjudge.net/problem/UVALive-3177
题意:(蓝书 P37)
思路:
一开始有想过用二分答案,但是找不到好方法判断一个数是否满足题目要求;
这里关键的就是贪心策略:如果有p个数,要判断是否满足条件,那么最好的方法就是奇数的人优先取最右边的数字,偶数的人优先取左边的数字,用这个条件去写二分答案的判断函数就能解决问题了;
把前a[1]的数设置为左边的数字,其他的设置为右边的数字,用left和right来表示第i个人左边取了几个数右边取了几个数,最后判断最后一个人 n 有没有取左边的数,如果有的话就false;(这个方法挺方便的)
代码:(一些需要注意的部分都写注释了)
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<sstream>
#include<vector>
#include<string>
#include<set>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define REP(i,n) for(int i=0;i<n;++i)
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;
}
typedef long long ll;
typedef unsigned long long ull;
const int Maxn = 1e5+10;
const long long LINF = 1e18;
const int INF = 0x3f3f3f3f;
const int Mod = 10001;
const double PI = acos(-1.0);
int a[Maxn],n,Left[Maxn],Right[Maxn];
bool ok (int x) { // 这里的ok 和下面的ok (蓝书的) 不同在于这里的ok函数是把一些非法的情况去掉了
if(x < a[1]) return false; // 比如左右的数字能取得取完还是不够要求的个数就false;
int le = a[1],ri = x-a[1]; // 不用去掉也可以AC
Left[1] = le; Right[1] = 0;
for (int i = 2; i <= n; ++i) {
if(i%2 != 0) { // 奇数优先取右边的数字
Right[i] = ri-Right[i-1] >= a[i] ? a[i] : ri-Right[i-1];
if(a[i]-Right[i] > le-Left[i-1]) return false;
Left[i] = a[i]-Right[i];
} else { // 偶数优先取左边的
Left[i] = le-Left[i-1] >= a[i] ? a[i] : le-Left[i-1];
if(a[i]-Left[i] > ri-Right[i-1]) return false;
Right[i] = a[i]-Left[i];
}
}
if(Left[n]) return false;
else return true;
}
/*
bool ok (int x) {
int le = a[1],ri = x-a[1];
Left[1] = le; Right[1] = 0;
for (int i = 2; i <= n; ++i) {
if(i%2 == 1) {
Right[i] = min(ri-Right[i-1],a[i]);
Left[i] = a[i]-Right[i];
} else {
Left[i] = min(le-Left[i-1],a[i]);
Right[i] = a[i]-Left[i];
}
}
return Left[n] == 0;
}*/
int main (void)
{
while (cin >> n && n) {
int maxn = 0;
for (int i = 1; i <= n; ++i) cin >> a[i];
a[n+1] = a[1]; // 这里需要注意了,因为是环形的,所以也要考虑a[n] 和 a[1]
if(n == 1) { cout << a[1] << endl; continue; } // 特判
int le = 0,ri = 0,mid;
for (int i = 1; i <= n; ++i) le = max(le,a[i]+a[i+1]); //下限
if(n%2 == 1) {
for (int i = 1; i <= n; ++i) ri = max(ri,a[i]*3); // 上限
while (le < ri) {
mid = le+(ri-le)/2;
if(ok(mid)) ri = mid;
else le = mid+1; // 这里的mid+1要注意了,上一篇同样讲二分答案的时候讲过
}
}
cout << le << endl;
}
return 0;
}