題解:看到題目,馬上YY了一個貪心:序列每個數減去初始序列的平均值然後求最大連續字段和。但是!這樣的盲目貪心是錯誤的
對於這樣一組數據:6 20 30 40 60 89 1來說,如果按照上述貪心法則,結果得到 20 30 1,正解應爲20 1
二分答案!
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
#define eps 1e-9
int a[100005];
double maxx,tot,s,sum;
double l,r,mid,ans;
int n,k;
bool check(double m) {
double p = 0, B, mx = -1e10;
for(int i=2;i<n;i++) {
B = a[i] - m;
if(p >= 0) B += p;
mx = max(mx, p = B);
}
return sum - n * m - mx <= 0;
}
void init()
{
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
scanf("%d",&a[i]);
sum+=a[i];
}
}
void work()
{
l=0,r=1e9;
while(r-l>=eps)
{
mid=(l+r)/2.0;
if(check(mid))
r=mid,ans=mid;
else l=mid;
}
printf("%.3lf",ans);
}
int main()
{
init();
work();
return 0;
}
//http://www.cnblogs.com/JSZX11556/p/4662515.html