Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

Let's expand the rule for f(j)f(j).

f(j)=(i=1n(1)i1ai)(i=1n(1)i1bi+j)f(j) = |(\sum_{i = 1}^{n} (-1)^{i - 1} \cdot a_i) - (\sum_{i = 1}^{n} (-1)^{i - 1} \cdot b_{i + j})|

Let's call the added value kk and the aa's alternating sum vv.

Note that for each query, adding kk to an even-length segment won't make a difference because they'll cancel themselves. Otherwise, vv will differ by kk (it's not canceled by the following element).

This means that we can precompute vv in O(N)\mathcal{O}(N) time.

What about bb? We can compute each segment of nn elements with two pointers, since bb's values never change.

However, checking every value of jj will surely TLE. Instead, we can notice that since we're calculating absolute value, we only care about the two closest elements on either side of it. Thus, we'll binary search on the alternating sums of bb.

Implementation

Time Complexity: O(N+(M+Q)logM)\mathcal{O}(N + (M + Q)\log M)

C++

#include <algorithm>
#include <iostream>
#include <vector>
using std::vector;
int main() {
int n;
int m;
int q;
std::cin >> n >> m >> q;

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!