【二分 贪心】bzoj3477: [Usaco2014 Mar]Sabotage:二分

科学二分姿势

Description

Farmer John's arch-nemesis, Farmer Paul, has decided to sabotage Farmer John's milking equipment! The milking equipment consists of a row of N (3 <= N <= 100,000) milking machines, where the ith machine produces M_i units of milk (1 <= M_i <= 10,000). Farmer Paul plans to disconnect a contiguous block of these machines -- from the ith machine up to the jth machine (2 <= i <= j <= N-1); note that Farmer Paul does not want to disconnect either the first or the last machine, since this will make his plot too easy to discover. Farmer Paul's goal is to minimize the average milk production of the remaining machines. Farmer Paul plans to remove at least 1 cow, even if it would be better for him to avoid sabotage entirely. Fortunately, Farmer John has learned of Farmer Paul's evil plot, and he is wondering how bad his milk production will suffer if the plot succeeds. Please help Farmer John figure out the minimum average milk production of the remaining machines if Farmer Paul does succeed.

约翰的牧场里有 N 台机器,第 i 台机器的工作能力为 Ai。保罗阴谋破坏一些机器,使得约翰的
工作效率变低。保罗可以任意选取一段编号连续的机器,使它们停止工作。但这样的破坏只能搞一次,
而且保罗无法破坏第一台或最后一台机器。请问他该破坏哪些机器才能让剩下机器的工作效率的平均
数最小?为了显示存在感,保罗至少必须破坏一台机器。

Input

* Line 1: The integer N.

* Lines 2..1+N: Line i+1 contains M_i.

Output

* Line 1: The lowest possible average Farmer Paul can achieve, rounded to 3 digits after the decimal point, and printed with 3 digits after the decimal point.


题目分析

显然极大/极小化特定值是要用二分的。但是这里要求平均数应该如何check呢?

check的基本模式当然就是依靠贪心地选取元素来判断是否满足限制。这里如果按照普通的思路求平均数,由于其受到所选元素个数的限制,check会变得不可做。

但是!我们有一种酷炫操作:二分平均数$x$没错,然后将每一个元素都减去$x$。这样一来,check要做的就是在原序列中找出一段前缀和一段后缀使得它们的和<=0.

我是直接写前后缀的,这样非常慢。

网上有一种更妙的方法就是等价于在序列中找最大子段和。

 1 #include<bits/stdc++.h>
 2 const int maxn = 100035;
 3 const double eps = 1e-6;
 4 
 5 int n,a[maxn];
 6 double f[maxn],g[maxn],b[maxn],ans;
 7 
 8 bool check(double x)
 9 {
10     f[0] = g[n+1] = 0;
11     for (int i=1; i<=n; i++) b[i] = a[i]-x, f[i] = 0, g[i] = 0;
12     for (int i=1; i<=n; i++) f[i] = f[i-1]+b[i];
13     for (int i=n; i>=1; i--) g[i] = g[i+1]+b[i];
14     f[0] = g[n+1] = 2e9;
15     for (int i=1; i<=n; i++) f[i] = std::min(f[i], f[i-1]);
16     for (int i=n; i>=1; i--) g[i] = std::min(g[i], g[i+1]);
17     for (int i=2; i<n-1; i++)
18         if (f[i]+g[i+1] < eps)
19             return 1;
20     return 0;
21 }
22 int main()
23 {
24     scanf("%d",&n);
25     for (int i=1; i<=n; i++) scanf("%d",&a[i]);
26     double l = 0, ans = r = 10000.0;
27     for (double mid=(l+r)/2; r-l > eps; mid=(l+r)/2)
28         if (check(mid)) ans = mid, r = mid-eps;
29         else l = mid+eps;
30     if (n==3) ans = std::min(ans, (a[3]+a[1])/2.0);
31     printf("%.3lf\n",ans);
32     return 0;
33 }

END

猜你喜欢

转载自www.cnblogs.com/antiquality/p/9296382.html