Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

We can binary search on real values to find the minimum average XX we can achieve.

Now, if we find the prefix sum array pref\texttt{pref} of the machine milk production array MM, consider the condition we need to achieve an average X\le X by removing the subarray (i,j](i, j]:

S(pref[j]pref[i])N(ji)X,\frac{S-\left(\texttt{pref}[j]-\texttt{pref}[i]\right)}{N-\left(j-i\right)}\le X,

where SS is the current sum of the array. After multiplying both sides by the denominator and isolating all terms involving ii, we get:

pref[i]XiX(Nj)S+pref[j].\texttt{pref}[i]-X\cdot i\le X\cdot\left(N-j\right)-S+\texttt{pref}[j].

For a fixed jj, we should try to minimize the left side expression. So we can iterate jj from 22 to N1N - 1 and keep a running minimum of the left side of the inequality. If the condition is satisfied, we can achieve an average X\le X.

Implementation

Time Complexity: O(Nlog(1ε))\mathcal{O}(N\log\left(\frac{1}{\varepsilon}\right)), where ε\varepsilon is the fixed error margin.

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("sabotage.in", "r", stdin);
freopen("sabotage.out", "w", stdout);
int n;
cin >> n;
vector<int> m(n);

Python

with open("sabotage.in", "r") as read:
n = int(read.readline())
m = [int(read.readline()) for i in range(n)]
pref_sum = [0]
for i in range(n):
pref_sum.append(pref_sum[-1] + m[i])
arr_sum = sum(m)

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!